Compare commits

...
Author SHA1 Message Date
Joao Matos 20c7478e60 Added System.IO.Compression implementation based on SharpCompress. 2014-05-12 19:41:00 +01:00
Joao Matos d2acd180ad Added SharpCompress Zip archive implementation.
This copy is based on our own fork at mono/sharpcompress.
2014-05-12 19:09:37 +01:00
95 changed files with 7227 additions and 40 deletions

No files matched your search

+2 -3
View File
@@ -3,8 +3,7 @@ SUBDIRS =
include ../../build/rules.make
LIBRARY = System.IO.Compression.dll
LIB_MCS_FLAGS = /r:System
NO_TEST = yes
LIB_MCS_FLAGS = /r:System /r:System.Core /unsafe
TEST_MCS_FLAGS = /r:System /r:System.Core
include ../../build/library.make
@@ -0,0 +1,206 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Common;
using SharpCompress.Reader;
namespace SharpCompress.Archive
{
internal abstract class AbstractArchive<TEntry, TVolume> : IArchive, IArchiveExtractionListener
where TEntry : IArchiveEntry
where TVolume : IVolume
{
private readonly LazyReadOnlyCollection<TVolume> lazyVolumes;
private readonly LazyReadOnlyCollection<TEntry> lazyEntries;
public event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>> EntryExtractionBegin;
public event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>> EntryExtractionEnd;
public event EventHandler<CompressedBytesReadEventArgs> CompressedBytesRead;
public event EventHandler<FilePartExtractionBeginEventArgs> FilePartExtractionBegin;
protected string Password { get; private set; }
#if !PORTABLE && !NETFX_CORE
internal AbstractArchive(ArchiveType type, FileInfo fileInfo, Options options, string password)
{
Type = type;
Password = password;
if (!fileInfo.Exists)
{
throw new ArgumentException("File does not exist: " + fileInfo.FullName);
}
options = (Options) FlagUtility.SetFlag(options, Options.KeepStreamsOpen, false);
lazyVolumes = new LazyReadOnlyCollection<TVolume>(LoadVolumes(fileInfo, options));
lazyEntries = new LazyReadOnlyCollection<TEntry>(LoadEntries(Volumes));
}
protected abstract IEnumerable<TVolume> LoadVolumes(FileInfo file, Options options);
#endif
internal AbstractArchive(ArchiveType type, IEnumerable<Stream> streams, Options options, string password)
{
Type = type;
Password = password;
lazyVolumes = new LazyReadOnlyCollection<TVolume>(LoadVolumes(streams.Select(CheckStreams), options));
lazyEntries = new LazyReadOnlyCollection<TEntry>(LoadEntries(Volumes));
}
internal AbstractArchive(ArchiveType type)
{
Type = type;
lazyVolumes = new LazyReadOnlyCollection<TVolume>(Enumerable.Empty<TVolume>());
lazyEntries = new LazyReadOnlyCollection<TEntry>(Enumerable.Empty<TEntry>());
}
public ArchiveType Type { get; private set; }
void IArchiveExtractionListener.FireEntryExtractionBegin(IArchiveEntry entry)
{
if (EntryExtractionBegin != null)
{
EntryExtractionBegin(this, new ArchiveExtractionEventArgs<IArchiveEntry>(entry));
}
}
void IArchiveExtractionListener.FireEntryExtractionEnd(IArchiveEntry entry)
{
if (EntryExtractionEnd != null)
{
EntryExtractionEnd(this, new ArchiveExtractionEventArgs<IArchiveEntry>(entry));
}
}
private static Stream CheckStreams(Stream stream)
{
if (!stream.CanSeek || !stream.CanRead)
{
throw new ArgumentException("Archive streams must be Readable and Seekable");
}
return stream;
}
/// <summary>
/// Returns an ReadOnlyCollection of all the RarArchiveEntries across the one or many parts of the RarArchive.
/// </summary>
/// <returns></returns>
public virtual ICollection<TEntry> Entries
{
get { return lazyEntries; }
}
/// <summary>
/// Returns an ReadOnlyCollection of all the RarArchiveVolumes across the one or many parts of the RarArchive.
/// </summary>
/// <returns></returns>
public ICollection<TVolume> Volumes
{
get { return lazyVolumes; }
}
/// <summary>
/// The total size of the files compressed in the archive.
/// </summary>
public long TotalSize
{
get { return Entries.Aggregate(0L, (total, cf) => total + cf.CompressedSize); }
}
protected abstract IEnumerable<TVolume> LoadVolumes(IEnumerable<Stream> streams, Options options);
protected abstract IEnumerable<TEntry> LoadEntries(IEnumerable<TVolume> volumes);
IEnumerable<IArchiveEntry> IArchive.Entries
{
get { return Entries.Cast<IArchiveEntry>(); }
}
IEnumerable<IVolume> IArchive.Volumes
{
get { return lazyVolumes.Cast<IVolume>(); }
}
private bool disposed;
public virtual void Dispose()
{
if (!disposed)
{
lazyVolumes.ForEach(v => v.Dispose());
lazyEntries.GetLoaded().Cast<Entry>().ForEach(x => x.Close());
disposed = true;
}
}
void IArchiveExtractionListener.EnsureEntriesLoaded()
{
lazyEntries.EnsureFullyLoaded();
lazyVolumes.EnsureFullyLoaded();
}
void IExtractionListener.FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes)
{
if (CompressedBytesRead != null)
{
CompressedBytesRead(this, new CompressedBytesReadEventArgs()
{
CurrentFilePartCompressedBytesRead = currentPartCompressedBytes,
CompressedBytesRead = compressedReadBytes
});
}
}
void IExtractionListener.FireFilePartExtractionBegin(string name, long size, long compressedSize)
{
if (FilePartExtractionBegin != null)
{
FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs()
{
CompressedSize = compressedSize,
Size = size,
Name = name,
});
}
}
/// <summary>
/// Use this method to extract all entries in an archive in order.
/// This is primarily for SOLID Rar Archives or 7Zip Archives as they need to be
/// extracted sequentially for the best performance.
///
/// This method will load all entry information from the archive.
///
/// WARNING: this will reuse the underlying stream for the archive. Errors may
/// occur if this is used at the same time as other extraction methods on this instance.
/// </summary>
/// <returns></returns>
public IReader ExtractAllEntries()
{
((IArchiveExtractionListener)this).EnsureEntriesLoaded();
return CreateReaderForSolidExtraction();
}
protected abstract IReader CreateReaderForSolidExtraction();
/// <summary>
/// Archive is SOLID (this means the Archive saved bytes by reusing information which helps for archives containing many small files).
/// </summary>
public virtual bool IsSolid
{
get { return false; }
}
/// <summary>
/// The archive can find all the parts of the archive needed to fully extract the archive. This forces the parsing of the entire archive.
/// </summary>
public bool IsComplete
{
get
{
((IArchiveExtractionListener)this).EnsureEntriesLoaded();
return Entries.All(x => x.IsComplete);
}
}
}
}
@@ -0,0 +1,100 @@
using System;
using System.IO;
using SharpCompress.Common;
namespace SharpCompress.Archive
{
internal static class AbstractWritableArchiveExtensions
{
public static void SaveTo<TEntry, TVolume>(this AbstractWritableArchive<TEntry, TVolume> writableArchive,
Stream stream, CompressionType compressionType)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
writableArchive.SaveTo(stream, new CompressionInfo {Type = compressionType});
}
#if !PORTABLE && !NETFX_CORE
public static void AddEntry<TEntry, TVolume>(this AbstractWritableArchive<TEntry, TVolume> writableArchive,
string entryPath, string filePath)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
var fileInfo = new FileInfo(filePath);
if (!fileInfo.Exists)
{
throw new FileNotFoundException("Could not AddEntry: " + filePath);
}
writableArchive.AddEntry(entryPath, new FileInfo(filePath).OpenRead(), true, fileInfo.Length,
fileInfo.LastWriteTime);
}
public static void SaveTo<TEntry, TVolume>(this AbstractWritableArchive<TEntry, TVolume> writableArchive,
string filePath, CompressionType compressionType)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
writableArchive.SaveTo(new FileInfo(filePath), new CompressionInfo {Type = compressionType});
}
public static void SaveTo<TEntry, TVolume>(this AbstractWritableArchive<TEntry, TVolume> writableArchive,
FileInfo fileInfo, CompressionType compressionType)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write))
{
writableArchive.SaveTo(stream, new CompressionInfo {Type = compressionType});
}
}
public static void SaveTo<TEntry, TVolume>(this AbstractWritableArchive<TEntry, TVolume> writableArchive,
string filePath, CompressionInfo compressionInfo)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
writableArchive.SaveTo(new FileInfo(filePath), compressionInfo);
}
public static void SaveTo<TEntry, TVolume>(this AbstractWritableArchive<TEntry, TVolume> writableArchive,
FileInfo fileInfo, CompressionInfo compressionInfo)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
using (var stream = fileInfo.Open(FileMode.Create, FileAccess.Write))
{
writableArchive.SaveTo(stream, compressionInfo);
}
}
public static void AddAllFromDirectory<TEntry, TVolume>(
this AbstractWritableArchive<TEntry, TVolume> writableArchive,
string filePath, string searchPattern = "*.*", SearchOption searchOption = SearchOption.AllDirectories)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
#if NET2
foreach (var path in Directory.GetFiles(filePath, searchPattern, searchOption))
#else
foreach (var path in Directory.EnumerateFiles(filePath, searchPattern, searchOption))
#endif
{
var fileInfo = new FileInfo(path);
writableArchive.AddEntry(path.Substring(filePath.Length), fileInfo.OpenRead(), true, fileInfo.Length,
fileInfo.LastWriteTime);
}
}
public static TEntry AddEntry<TEntry, TVolume>(this AbstractWritableArchive<TEntry, TVolume> writableArchive, string key, FileInfo fileInfo)
where TEntry : IArchiveEntry
where TVolume : IVolume
{
if (!fileInfo.Exists)
{
throw new ArgumentException("FileInfo does not exist.");
}
return writableArchive.AddEntry(key, fileInfo.OpenRead(), true, fileInfo.Length, fileInfo.LastWriteTime);
}
#endif
}
}
@@ -0,0 +1,139 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Common;
namespace SharpCompress.Archive
{
internal abstract class AbstractWritableArchive<TEntry, TVolume> : AbstractArchive<TEntry, TVolume>
where TEntry : IArchiveEntry
where TVolume : IVolume
{
private readonly List<TEntry> newEntries = new List<TEntry>();
private readonly List<TEntry> removedEntries = new List<TEntry>();
private readonly List<TEntry> modifiedEntries = new List<TEntry>();
private bool hasModifications;
internal AbstractWritableArchive(ArchiveType type)
: base(type)
{
}
internal AbstractWritableArchive(ArchiveType type, Stream stream, Options options)
: base(type, stream.AsEnumerable(), options, null)
{
}
#if !PORTABLE && !NETFX_CORE
internal AbstractWritableArchive(ArchiveType type, FileInfo fileInfo, Options options)
: base(type, fileInfo, options, null)
{
}
#endif
public override ICollection<TEntry> Entries
{
get
{
if (hasModifications)
{
return modifiedEntries;
}
return base.Entries;
}
}
private void RebuildModifiedCollection()
{
hasModifications = true;
newEntries.RemoveAll(v => removedEntries.Contains(v));
modifiedEntries.Clear();
modifiedEntries.AddRange(OldEntries.Concat(newEntries));
}
private IEnumerable<TEntry> OldEntries
{
get { return base.Entries.Where(x => !removedEntries.Contains(x)); }
}
public void RemoveEntry(TEntry entry)
{
if (!removedEntries.Contains(entry))
{
removedEntries.Add(entry);
RebuildModifiedCollection();
}
}
public TEntry AddEntry(string key, Stream source,
long size = 0, DateTime? modified = null)
{
return AddEntry(key, source, false, size, modified);
}
public TEntry AddEntry(string key, Stream source, bool closeStream,
long size = 0, DateTime? modified = null)
{
if (key.StartsWith("/")
|| key.StartsWith("\\"))
{
key = key.Substring(1);
}
if (DoesKeyMatchExisting(key))
{
throw new ArchiveException("Cannot add entry with duplicate key: " + key);
}
var entry = CreateEntry(key, source, size, modified, closeStream);
newEntries.Add(entry);
RebuildModifiedCollection();
return entry;
}
private bool DoesKeyMatchExisting(string key)
{
foreach (var path in Entries.Select(x => x.Key))
{
var p = path.Replace('/','\\');
if (p.StartsWith("\\"))
{
p = p.Substring(1);
}
return string.Equals(p, key, StringComparison.OrdinalIgnoreCase);
}
return false;
}
public void SaveTo(Stream stream, CompressionInfo compressionType)
{
//reset streams of new entries
newEntries.Cast<IWritableArchiveEntry>().ForEach(x => x.Stream.Seek(0, SeekOrigin.Begin));
SaveTo(stream, compressionType, OldEntries, newEntries);
}
protected TEntry CreateEntry(string key, Stream source, long size, DateTime? modified,
bool closeStream)
{
if (!source.CanRead || !source.CanSeek)
{
throw new ArgumentException("Streams must be readable and seekable to use the Writing Archive API");
}
return CreateEntryInternal(key, source, size, modified, closeStream);
}
protected abstract TEntry CreateEntryInternal(string key, Stream source, long size, DateTime? modified,
bool closeStream);
protected abstract void SaveTo(Stream stream, CompressionInfo compressionType,
IEnumerable<TEntry> oldEntries, IEnumerable<TEntry> newEntries);
public override void Dispose()
{
base.Dispose();
newEntries.Cast<Entry>().ForEach(x => x.Close());
removedEntries.Cast<Entry>().ForEach(x => x.Close());
modifiedEntries.Cast<Entry>().ForEach(x => x.Close());
}
}
}
@@ -0,0 +1,194 @@
using System;
using System.IO;
#if GZIP
using SharpCompress.Archive.GZip;
#endif
#if RAR
using SharpCompress.Archive.Rar;
#endif
#if SEVENZIP
using SharpCompress.Archive.SevenZip;
#endif
#if TAR
using SharpCompress.Archive.Tar;
#endif
using SharpCompress.Archive.Zip;
using SharpCompress.Common;
namespace SharpCompress.Archive
{
internal class ArchiveFactory
{
/// <summary>
/// Opens an Archive for random access
/// </summary>
/// <param name="stream"></param>
/// <param name="options"></param>
/// <returns></returns>
public static IArchive Open(Stream stream, Options options = Options.KeepStreamsOpen)
{
stream.CheckNotNull("stream");
if (!stream.CanRead || !stream.CanSeek)
{
throw new ArgumentException("Stream should be readable and seekable");
}
if (ZipArchive.IsZipFile(stream, null))
{
stream.Seek(0, SeekOrigin.Begin);
return ZipArchive.Open(stream, options, null);
}
#if RAR
stream.Seek(0, SeekOrigin.Begin);
if (RarArchive.IsRarFile(stream, Options.LookForHeader | Options.KeepStreamsOpen))
{
stream.Seek(0, SeekOrigin.Begin);
return RarArchive.Open(stream, options);
}
#endif
#if TAR
stream.Seek(0, SeekOrigin.Begin);
if (TarArchive.IsTarFile(stream))
{
stream.Seek(0, SeekOrigin.Begin);
return TarArchive.Open(stream, options);
}
#endif
#if SEVENZIP
stream.Seek(0, SeekOrigin.Begin);
if (SevenZipArchive.IsSevenZipFile(stream))
{
stream.Seek(0, SeekOrigin.Begin);
return SevenZipArchive.Open(stream, options);
}
#endif
#if GZIP
stream.Seek(0, SeekOrigin.Begin);
if (GZipArchive.IsGZipFile(stream))
{
stream.Seek(0, SeekOrigin.Begin);
return GZipArchive.Open(stream, options);
}
#endif
throw new InvalidOperationException("Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip");
}
public static IArchive Create(ArchiveType type)
{
switch (type)
{
case ArchiveType.Zip:
{
return ZipArchive.Create();
}
#if TAR
case ArchiveType.Tar:
{
return TarArchive.Create();
}
#endif
default:
{
throw new NotSupportedException("Cannot create Archives of type: " + type);
}
}
}
#if !PORTABLE && !NETFX_CORE
/// <summary>
/// Constructor expects a filepath to an existing file.
/// </summary>
/// <param name="filePath"></param>
public static IArchive Open(string filePath)
{
return Open(filePath, Options.None);
}
/// <summary>
/// Constructor with a FileInfo object to an existing file.
/// </summary>
/// <param name="fileInfo"></param>
public static IArchive Open(FileInfo fileInfo)
{
return Open(fileInfo, Options.None);
}
/// <summary>
/// Constructor expects a filepath to an existing file.
/// </summary>
/// <param name="filePath"></param>
/// <param name="options"></param>
public static IArchive Open(string filePath, Options options)
{
filePath.CheckNotNullOrEmpty("filePath");
return Open(new FileInfo(filePath), options);
}
/// <summary>
/// Constructor with a FileInfo object to an existing file.
/// </summary>
/// <param name="fileInfo"></param>
/// <param name="options"></param>
public static IArchive Open(FileInfo fileInfo, Options options)
{
fileInfo.CheckNotNull("fileInfo");
using (var stream = fileInfo.OpenRead())
{
if (ZipArchive.IsZipFile(stream, null))
{
stream.Dispose();
return ZipArchive.Open(fileInfo, options, null);
}
#if RAR
stream.Seek(0, SeekOrigin.Begin);
if (RarArchive.IsRarFile(stream, Options.LookForHeader | Options.KeepStreamsOpen))
{
stream.Dispose();
return RarArchive.Open(fileInfo, options);
}
#endif
#if TAR
stream.Seek(0, SeekOrigin.Begin);
if (TarArchive.IsTarFile(stream))
{
stream.Dispose();
return TarArchive.Open(fileInfo, options);
}
#endif
#if SEVENZIP
stream.Seek(0, SeekOrigin.Begin);
if (SevenZipArchive.IsSevenZipFile(stream))
{
stream.Dispose();
return SevenZipArchive.Open(fileInfo, options);
}
#endif
#if GZIP
stream.Seek(0, SeekOrigin.Begin);
if (GZipArchive.IsGZipFile(stream))
{
stream.Dispose();
return GZipArchive.Open(fileInfo, options);
}
#endif
throw new InvalidOperationException("Cannot determine compressed stream type.");
}
}
/// <summary>
/// Extract to specific directory, retaining filename
/// </summary>
public static void WriteToDirectory(string sourceArchive, string destinationDirectory,
ExtractOptions options = ExtractOptions.Overwrite)
{
using (IArchive archive = Open(sourceArchive))
{
foreach (IArchiveEntry entry in archive.Entries)
{
entry.WriteToDirectory(destinationDirectory, options);
}
}
}
#endif
}
}
@@ -0,0 +1,22 @@
using System.Linq;
using SharpCompress.Common;
namespace SharpCompress.Archive
{
internal static class IArchiveExtensions
{
#if !PORTABLE && !NETFX_CORE
/// <summary>
/// Extract to specific directory, retaining filename
/// </summary>
public static void WriteToDirectory(this IArchive archive, string destinationDirectory,
ExtractOptions options = ExtractOptions.Overwrite)
{
foreach (IArchiveEntry entry in archive.Entries.Where(x => !x.IsDirectory))
{
entry.WriteToDirectory(destinationDirectory, options);
}
}
#endif
}
}
@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using SharpCompress.Common;
using SharpCompress.Reader;
namespace SharpCompress.Archive
{
internal interface IArchive : IDisposable
{
event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>> EntryExtractionBegin;
event EventHandler<ArchiveExtractionEventArgs<IArchiveEntry>> EntryExtractionEnd;
event EventHandler<CompressedBytesReadEventArgs> CompressedBytesRead;
event EventHandler<FilePartExtractionBeginEventArgs> FilePartExtractionBegin;
IEnumerable<IArchiveEntry> Entries { get; }
long TotalSize { get; }
IEnumerable<IVolume> Volumes { get; }
ArchiveType Type { get; }
/// <summary>
/// Use this method to extract all entries in an archive in order.
/// This is primarily for SOLID Rar Archives or 7Zip Archives as they need to be
/// extracted sequentially for the best performance.
/// </summary>
/// <returns></returns>
IReader ExtractAllEntries();
/// <summary>
/// Archive is SOLID (this means the Archive saved bytes by reusing information which helps for archives containing many small files).
/// Rar Archives can be SOLID while all 7Zip archives are considered SOLID.
/// </summary>
bool IsSolid { get; }
/// <summary>
/// This checks to see if all the known entries have IsComplete = true
/// </summary>
bool IsComplete { get; }
}
}
@@ -0,0 +1,89 @@
using System.IO;
using SharpCompress.Common;
using SharpCompress.IO;
namespace SharpCompress.Archive
{
internal static class IArchiveEntryExtensions
{
public static void WriteTo(this IArchiveEntry archiveEntry, Stream streamToWriteTo)
{
if (archiveEntry.Archive.Type == ArchiveType.Rar && archiveEntry.Archive.IsSolid)
{
throw new InvalidFormatException("Cannot use Archive random access on SOLID Rar files.");
}
if (archiveEntry.IsDirectory)
{
throw new ExtractionException("Entry is a file directory and cannot be extracted.");
}
var streamListener = archiveEntry.Archive as IArchiveExtractionListener;
streamListener.EnsureEntriesLoaded();
streamListener.FireEntryExtractionBegin(archiveEntry);
streamListener.FireFilePartExtractionBegin(archiveEntry.Key, archiveEntry.Size, archiveEntry.CompressedSize);
var entryStream = archiveEntry.OpenEntryStream();
if (entryStream == null)
{
return;
}
using(entryStream)
using (Stream s = new ListeningStream(streamListener, entryStream))
{
s.TransferTo(streamToWriteTo);
}
streamListener.FireEntryExtractionEnd(archiveEntry);
}
#if !PORTABLE && !NETFX_CORE
/// <summary>
/// Extract to specific directory, retaining filename
/// </summary>
public static void WriteToDirectory(this IArchiveEntry entry, string destinationDirectory,
ExtractOptions options = ExtractOptions.Overwrite)
{
string destinationFileName;
string file = Path.GetFileName(entry.Key);
if (options.HasFlag(ExtractOptions.ExtractFullPath))
{
string folder = Path.GetDirectoryName(entry.Key);
string destdir = Path.Combine(destinationDirectory, folder);
if (!Directory.Exists(destdir))
{
Directory.CreateDirectory(destdir);
}
destinationFileName = Path.Combine(destdir, file);
}
else
{
destinationFileName = Path.Combine(destinationDirectory, file);
}
entry.WriteToFile(destinationFileName, options);
}
/// <summary>
/// Extract to specific file
/// </summary>
public static void WriteToFile(this IArchiveEntry entry, string destinationFileName,
ExtractOptions options = ExtractOptions.Overwrite)
{
if (entry.IsDirectory)
{
return;
}
FileMode fm = FileMode.Create;
if (!options.HasFlag(ExtractOptions.Overwrite))
{
fm = FileMode.CreateNew;
}
using (FileStream fs = File.Open(destinationFileName, fm))
{
entry.WriteTo(fs);
}
}
#endif
}
}
@@ -0,0 +1,24 @@
using System.IO;
using SharpCompress.Common;
namespace SharpCompress.Archive
{
internal interface IArchiveEntry : IEntry
{
/// <summary>
/// Opens the current entry as a stream that will decompress as it is read.
/// Read the entire stream or use SkipEntry on EntryStream.
/// </summary>
Stream OpenEntryStream();
/// <summary>
/// The archive can find all the parts of the archive needed to extract this entry.
/// </summary>
bool IsComplete { get; }
/// <summary>
/// The archive instance this entry belongs to
/// </summary>
IArchive Archive { get; }
}
}
@@ -0,0 +1,11 @@
using SharpCompress.Common;
namespace SharpCompress.Archive
{
internal interface IArchiveExtractionListener : IExtractionListener
{
void EnsureEntriesLoaded();
void FireEntryExtractionBegin(IArchiveEntry entry);
void FireEntryExtractionEnd(IArchiveEntry entry);
}
}
@@ -0,0 +1,9 @@
using System.IO;
namespace SharpCompress.Archive
{
internal interface IWritableArchiveEntry
{
Stream Stream { get; }
}
}
@@ -0,0 +1,245 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Common;
using SharpCompress.Common.Zip;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.Compressor.Deflate;
using SharpCompress.Reader;
using SharpCompress.Reader.Zip;
using SharpCompress.Writer.Zip;
namespace SharpCompress.Archive.Zip
{
internal class ZipArchive : AbstractWritableArchive<ZipArchiveEntry, ZipVolume>
{
private readonly SeekableZipHeaderFactory headerFactory;
/// <summary>
/// Gets or sets the compression level applied to files added to the archive,
/// if the compression method is set to deflate
/// </summary>
public CompressionLevel DeflateCompressionLevel { get; set; }
#if !PORTABLE && !NETFX_CORE
/// <summary>
/// Constructor expects a filepath to an existing file.
/// </summary>
/// <param name="filePath"></param>
/// <param name="password"></param>
public static ZipArchive Open(string filePath, string password = null)
{
return Open(filePath, Options.None, password);
}
/// <summary>
/// Constructor with a FileInfo object to an existing file.
/// </summary>
/// <param name="fileInfo"></param>
/// <param name="password"></param>
public static ZipArchive Open(FileInfo fileInfo, string password = null)
{
return Open(fileInfo, Options.None, password);
}
/// <summary>
/// Constructor expects a filepath to an existing file.
/// </summary>
/// <param name="filePath"></param>
/// <param name="options"></param>
/// <param name="password"></param>
public static ZipArchive Open(string filePath, Options options, string password = null)
{
filePath.CheckNotNullOrEmpty("filePath");
return Open(new FileInfo(filePath), options, password);
}
/// <summary>
/// Constructor with a FileInfo object to an existing file.
/// </summary>
/// <param name="fileInfo"></param>
/// <param name="options"></param>
/// <param name="password"></param>
public static ZipArchive Open(FileInfo fileInfo, Options options, string password = null)
{
fileInfo.CheckNotNull("fileInfo");
return new ZipArchive(fileInfo, options, password);
}
#endif
/// <summary>
/// Takes a seekable Stream as a source
/// </summary>
/// <param name="stream"></param>
/// <param name="password"></param>
public static ZipArchive Open(Stream stream, string password = null)
{
stream.CheckNotNull("stream");
return Open(stream, Options.None, password);
}
/// <summary>
/// Takes a seekable Stream as a source
/// </summary>
/// <param name="stream"></param>
/// <param name="options"></param>
/// <param name="password"></param>
public static ZipArchive Open(Stream stream, Options options, string password = null)
{
stream.CheckNotNull("stream");
return new ZipArchive(stream, options, password);
}
#if !PORTABLE && !NETFX_CORE
public static bool IsZipFile(string filePath, string password = null)
{
return IsZipFile(new FileInfo(filePath), password);
}
public static bool IsZipFile(FileInfo fileInfo, string password = null)
{
if (!fileInfo.Exists)
{
return false;
}
using (Stream stream = fileInfo.OpenRead())
{
return IsZipFile(stream, password);
}
}
#endif
public static bool IsZipFile(Stream stream, string password = null)
{
StreamingZipHeaderFactory headerFactory = new StreamingZipHeaderFactory(password);
try
{
ZipHeader header =
headerFactory.ReadStreamHeader(stream).FirstOrDefault(x => x.ZipHeaderType != ZipHeaderType.Split);
if (header == null)
{
return false;
}
return Enum.IsDefined(typeof (ZipHeaderType), header.ZipHeaderType);
}
catch (CryptographicException)
{
return true;
}
catch
{
return false;
}
}
#if !PORTABLE && !NETFX_CORE
/// <summary>
/// Constructor with a FileInfo object to an existing file.
/// </summary>
/// <param name="fileInfo"></param>
/// <param name="options"></param>
/// <param name="password"></param>
internal ZipArchive(FileInfo fileInfo, Options options, string password = null)
: base(ArchiveType.Zip, fileInfo, options)
{
headerFactory = new SeekableZipHeaderFactory(password);
}
protected override IEnumerable<ZipVolume> LoadVolumes(FileInfo file, Options options)
{
if (FlagUtility.HasFlag(options, Options.KeepStreamsOpen))
{
options = (Options)FlagUtility.SetFlag(options, Options.KeepStreamsOpen, false);
}
return new ZipVolume(file.OpenRead(), options).AsEnumerable();
}
#endif
internal ZipArchive()
: base(ArchiveType.Zip)
{
}
/// <summary>
/// Takes multiple seekable Streams for a multi-part archive
/// </summary>
/// <param name="stream"></param>
/// <param name="options"></param>
/// <param name="password"></param>
internal ZipArchive(Stream stream, Options options, string password = null)
: base(ArchiveType.Zip, stream, options)
{
headerFactory = new SeekableZipHeaderFactory(password);
}
protected override IEnumerable<ZipVolume> LoadVolumes(IEnumerable<Stream> streams, Options options)
{
return new ZipVolume(streams.First(), options).AsEnumerable();
}
protected override IEnumerable<ZipArchiveEntry> LoadEntries(IEnumerable<ZipVolume> volumes)
{
var volume = volumes.Single();
Stream stream = volume.Stream;
foreach (ZipHeader h in headerFactory.ReadSeekableHeader(stream))
{
if (h != null)
{
switch (h.ZipHeaderType)
{
case ZipHeaderType.DirectoryEntry:
{
yield return new ZipArchiveEntry(this,
new SeekableZipFilePart(headerFactory,
h as DirectoryEntryHeader,
stream));
}
break;
case ZipHeaderType.DirectoryEnd:
{
byte[] bytes = (h as DirectoryEndHeader).Comment;
volume.Comment = ArchiveEncoding.Default.GetString(bytes, 0, bytes.Length);
yield break;
}
}
}
}
}
protected override void SaveTo(Stream stream, CompressionInfo compressionInfo,
IEnumerable<ZipArchiveEntry> oldEntries,
IEnumerable<ZipArchiveEntry> newEntries)
{
using (var writer = new ZipWriter(stream, compressionInfo, string.Empty))
{
foreach (var entry in oldEntries.Concat(newEntries)
.Where(x => !x.IsDirectory))
{
using (var entryStream = entry.OpenEntryStream())
{
writer.Write(entry.Key, entryStream, entry.LastModifiedTime, string.Empty);
}
}
}
}
protected override ZipArchiveEntry CreateEntryInternal(string filePath, Stream source, long size, DateTime? modified,
bool closeStream)
{
return new ZipWritableArchiveEntry(this, source, filePath, size, modified, closeStream);
}
public static ZipArchive Create()
{
return new ZipArchive();
}
protected override IReader CreateReaderForSolidExtraction()
{
var stream = Volumes.Single().Stream;
stream.Position = 0;
return ZipReader.Open(stream);
}
}
}
@@ -0,0 +1,36 @@
using System.IO;
using System.Linq;
using SharpCompress.Common.Zip;
namespace SharpCompress.Archive.Zip
{
internal class ZipArchiveEntry : ZipEntry, IArchiveEntry
{
internal ZipArchiveEntry(ZipArchive archive, SeekableZipFilePart part)
: base(part)
{
Archive = archive;
}
public virtual Stream OpenEntryStream()
{
return Parts.Single().GetCompressedStream();
}
#region IArchiveEntry Members
public IArchive Archive { get; private set; }
public bool IsComplete
{
get { return true; }
}
#endregion
public string Comment
{
get { return (Parts.Single() as SeekableZipFilePart).Comment; }
}
}
}
@@ -0,0 +1,113 @@
using System;
using System.Collections.Generic;
using System.IO;
using SharpCompress.Common;
using SharpCompress.IO;
namespace SharpCompress.Archive.Zip
{
internal class ZipWritableArchiveEntry : ZipArchiveEntry, IWritableArchiveEntry
{
private readonly string path;
private readonly long size;
private readonly DateTime? lastModified;
private readonly bool closeStream;
private readonly Stream stream;
private bool isDisposed;
internal ZipWritableArchiveEntry(ZipArchive archive, Stream stream, string path, long size,
DateTime? lastModified, bool closeStream)
: base(archive, null)
{
this.stream = stream;
this.path = path;
this.size = size;
this.lastModified = lastModified;
this.closeStream = closeStream;
}
public override uint Crc
{
get { return 0; }
}
public override string Key
{
get { return path; }
}
public override long CompressedSize
{
get { return 0; }
}
public override long Size
{
get { return size; }
}
public override DateTime? LastModifiedTime
{
get { return lastModified; }
}
public override DateTime? CreatedTime
{
get { return null; }
}
public override DateTime? LastAccessedTime
{
get { return null; }
}
public override DateTime? ArchivedTime
{
get { return null; }
}
public override bool IsEncrypted
{
get { return false; }
}
public override bool IsDirectory
{
get { return false; }
}
public override bool IsSplit
{
get { return false; }
}
internal override IEnumerable<FilePart> Parts
{
get { throw new NotImplementedException(); }
}
Stream IWritableArchiveEntry.Stream
{
get
{
return stream;
}
}
public override Stream OpenEntryStream()
{
//ensure new stream is at the start, this could be reset
stream.Seek(0, SeekOrigin.Begin);
return new NonDisposingStream(stream);
}
internal override void Close()
{
if (closeStream && !isDisposed)
{
stream.Dispose();
isDisposed = true;
}
}
}
}
@@ -0,0 +1,29 @@
using System.Globalization;
using System.Text;
namespace SharpCompress.Common
{
internal class ArchiveEncoding
{
/// <summary>
/// Default encoding to use when archive format doesn't specify one.
/// </summary>
public static Encoding Default;
/// <summary>
/// Encoding used by encryption schemes which don't comply with RFC 2898.
/// </summary>
public static Encoding Password;
static ArchiveEncoding()
{
#if PORTABLE || NETFX_CORE
Default = Encoding.UTF8;
Password = Encoding.UTF8;
#else
Default = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage);
Password = Encoding.Default;
#endif
}
}
}
@@ -0,0 +1,12 @@
using System;
namespace SharpCompress.Common
{
internal class ArchiveException : Exception
{
public ArchiveException(string message)
: base(message)
{
}
}
}
@@ -0,0 +1,14 @@
using System;
namespace SharpCompress.Common
{
internal class ArchiveExtractionEventArgs<T> : EventArgs
{
internal ArchiveExtractionEventArgs(T entry)
{
Item = entry;
}
public T Item { get; private set; }
}
}
@@ -0,0 +1,11 @@
namespace SharpCompress.Common
{
internal enum ArchiveType
{
Rar,
Zip,
Tar,
SevenZip,
GZip,
}
}
@@ -0,0 +1,17 @@
using System;
namespace SharpCompress.Common
{
internal class CompressedBytesReadEventArgs : EventArgs
{
/// <summary>
/// Compressed bytes read for the current entry
/// </summary>
public long CompressedBytesRead { get; internal set; }
/// <summary>
/// Current file part read for Multipart files (e.g. Rar)
/// </summary>
public long CurrentFilePartCompressedBytesRead { get; internal set; }
}
}
@@ -0,0 +1,30 @@
using SharpCompress.Compressor.Deflate;
namespace SharpCompress.Common
{
/// <summary>
/// Detailed compression properties when saving.
/// </summary>
internal class CompressionInfo
{
public CompressionInfo()
{
DeflateCompressionLevel = CompressionLevel.Default;
}
/// <summary>
/// The algorthm to use. Must be valid for the format type.
/// </summary>
public CompressionType Type { get; set; }
/// <summary>
/// When CompressionType.Deflate is used, this property is referenced. Defaults to CompressionLevel.Default.
/// </summary>
public CompressionLevel DeflateCompressionLevel { get; set; }
public static implicit operator CompressionInfo(CompressionType compressionType)
{
return new CompressionInfo() {Type = compressionType};
}
}
}
@@ -0,0 +1,16 @@
namespace SharpCompress.Common
{
internal enum CompressionType
{
None,
GZip,
BZip2,
PPMd,
Deflate,
Rar,
LZMA,
BCJ,
BCJ2,
Unknown,
}
}
@@ -0,0 +1,12 @@
using System;
namespace SharpCompress.Common
{
internal class CryptographicException : Exception
{
public CryptographicException(string message)
: base(message)
{
}
}
}
@@ -0,0 +1,76 @@
using System;
using System.Collections.Generic;
namespace SharpCompress.Common
{
internal abstract class Entry : IEntry
{
/// <summary>
/// The File's 32 bit CRC Hash
/// </summary>
public abstract uint Crc { get; }
/// <summary>
/// The string key of the file internal to the Archive.
/// </summary>
public abstract string Key { get; }
/// <summary>
/// The compressed file size
/// </summary>
public abstract long CompressedSize { get; }
/// <summary>
/// The compression type
/// </summary>
public abstract CompressionType CompressionType { get; }
/// <summary>
/// The uncompressed file size
/// </summary>
public abstract long Size { get; }
/// <summary>
/// The entry last modified time in the archive, if recorded
/// </summary>
public abstract DateTime? LastModifiedTime { get; set; }
/// <summary>
/// The entry create time in the archive, if recorded
/// </summary>
public abstract DateTime? CreatedTime { get; }
/// <summary>
/// The entry last accessed time in the archive, if recorded
/// </summary>
public abstract DateTime? LastAccessedTime { get; }
/// <summary>
/// The entry time whend archived, if recorded
/// </summary>
public abstract DateTime? ArchivedTime { get; }
/// <summary>
/// Entry is password protected and encrypted and cannot be extracted.
/// </summary>
public abstract bool IsEncrypted { get; }
/// <summary>
/// Entry is password protected and encrypted and cannot be extracted.
/// </summary>
public abstract bool IsDirectory { get; }
/// <summary>
/// Entry is split among multiple volumes
/// </summary>
public abstract bool IsSplit { get; }
internal abstract IEnumerable<FilePart> Parts { get; }
internal bool IsSolid { get; set; }
internal virtual void Close()
{
}
}
}
@@ -0,0 +1,101 @@
using System;
using System.IO;
namespace SharpCompress.Common
{
internal class EntryStream : Stream
{
private Stream stream;
private bool completed;
private bool isDisposed;
internal EntryStream(Stream stream)
{
this.stream = stream;
}
/// <summary>
/// When reading a stream from OpenEntryStream, the stream must be completed so use this to finish reading the entire entry.
/// </summary>
public void SkipEntry()
{
var buffer = new byte[4096];
while (Read(buffer, 0, buffer.Length) > 0)
{
}
completed = true;
}
protected override void Dispose(bool disposing)
{
if (!completed)
{
throw new InvalidOperationException(
"EntryStream has not been fully consumed. Read the entire stream or use SkipEntry.");
}
if (isDisposed)
{
return;
}
isDisposed = true;
base.Dispose(disposing);
stream.Dispose();
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
throw new System.NotImplementedException();
}
public override long Length
{
get { throw new System.NotImplementedException(); }
}
public override long Position
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
int read = stream.Read(buffer, offset, count);
if (read <= 0)
{
completed = true;
}
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new System.NotImplementedException();
}
public override void SetLength(long value)
{
throw new System.NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new System.NotImplementedException();
}
}
}
@@ -0,0 +1,20 @@
using System;
namespace SharpCompress.Common
{
[Flags]
internal enum ExtractOptions
{
None,
/// <summary>
/// overwrite target if it exists
/// </summary>
Overwrite,
/// <summary>
/// extract with internal directory structure
/// </summary>
ExtractFullPath,
}
}
@@ -0,0 +1,17 @@
using System;
namespace SharpCompress.Common
{
internal class ExtractionException : Exception
{
public ExtractionException(string message)
: base(message)
{
}
public ExtractionException(string message, Exception inner)
: base(message, inner)
{
}
}
}
@@ -0,0 +1,12 @@
using System.IO;
namespace SharpCompress.Common
{
internal abstract class FilePart
{
internal abstract string FilePartName { get; }
internal abstract Stream GetCompressedStream();
internal abstract Stream GetRawStream();
}
}
@@ -0,0 +1,22 @@
using System;
namespace SharpCompress.Common
{
internal class FilePartExtractionBeginEventArgs : EventArgs
{
/// <summary>
/// File name for the part for the current entry
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// Uncompressed size of the current entry in the part
/// </summary>
public long Size { get; internal set; }
/// <summary>
/// Compressed size of the current entry in the part
/// </summary>
public long CompressedSize { get; internal set; }
}
}
@@ -0,0 +1,130 @@
using System;
namespace SharpCompress.Common
{
internal static class FlagUtility
{
/// <summary>
/// Returns true if the flag is set on the specified bit field.
/// Currently only works with 32-bit bitfields.
/// </summary>
/// <typeparam name="T">Enumeration with Flags attribute</typeparam>
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag<T>(long bitField, T flag)
where T : struct
{
return HasFlag(bitField, flag);
}
/// <summary>
/// Returns true if the flag is set on the specified bit field.
/// Currently only works with 32-bit bitfields.
/// </summary>
/// <typeparam name="T">Enumeration with Flags attribute</typeparam>
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag<T>(ulong bitField, T flag)
where T : struct
{
return HasFlag(bitField, flag);
}
/// <summary>
/// Returns true if the flag is set on the specified bit field.
/// Currently only works with 32-bit bitfields.
/// </summary>
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag(ulong bitField, ulong flag)
{
return ((bitField & flag) == flag);
}
public static bool HasFlag(short bitField, short flag)
{
return ((bitField & flag) == flag);
}
#if PORTABLE
/// <summary>
/// Generically checks enums in a Windows Phone 7 enivronment
/// </summary>
/// <param name="enumVal"></param>
/// <param name="flag"></param>
/// <returns></returns>
public static bool HasFlag(this Enum enumVal, Enum flag)
{
if (enumVal.GetHashCode() > 0) //GetHashCode returns the enum value. But it's something very crazy if not set beforehand
{
ulong num = Convert.ToUInt64(flag.GetHashCode());
return ((Convert.ToUInt64(enumVal.GetHashCode()) & num) == num);
}
else
{
return false;
}
}
#endif
/// <summary>
/// Returns true if the flag is set on the specified bit field.
/// Currently only works with 32-bit bitfields.
/// </summary>
/// <typeparam name="T">Enumeration with Flags attribute</typeparam>
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag<T>(T bitField, T flag)
where T : struct
{
return HasFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag));
}
/// <summary>
/// Returns true if the flag is set on the specified bit field.
/// Currently only works with 32-bit bitfields.
/// </summary>
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to test</param>
/// <returns></returns>
public static bool HasFlag(long bitField, long flag)
{
return ((bitField & flag) == flag);
}
/// <summary>
/// Sets a bit-field to either on or off for the specified flag.
/// </summary>
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to change</param>
/// <param name="on">bool</param>
/// <returns>The flagged variable with the flag changed</returns>
public static long SetFlag(long bitField, long flag, bool @on)
{
if (@on)
{
return bitField | flag;
}
return bitField & (~flag);
}
/// <summary>
/// Sets a bit-field to either on or off for the specified flag.
/// </summary>
/// <typeparam name="T">Enumeration with Flags attribute</typeparam>
/// <param name="bitField">Flagged variable</param>
/// <param name="flag">Flag to change</param>
/// <param name="on">bool</param>
/// <returns>The flagged variable with the flag changed</returns>
public static long SetFlag<T>(T bitField, T flag, bool @on)
where T : struct
{
return SetFlag(Convert.ToInt64(bitField), Convert.ToInt64(flag), @on);
}
}
}
@@ -0,0 +1,20 @@
using System;
namespace SharpCompress.Common
{
internal interface IEntry
{
CompressionType CompressionType { get; }
DateTime? ArchivedTime { get; }
long CompressedSize { get; }
uint Crc { get; }
DateTime? CreatedTime { get; }
string Key { get; }
bool IsDirectory { get; }
bool IsEncrypted { get; }
bool IsSplit { get; }
DateTime? LastAccessedTime { get; }
DateTime? LastModifiedTime { get; set; }
long Size { get; }
}
}
@@ -0,0 +1,8 @@
namespace SharpCompress.Common
{
internal interface IExtractionListener
{
void FireFilePartExtractionBegin(string name, long size, long compressedSize);
void FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes);
}
}
@@ -0,0 +1,11 @@
using System;
#if !PORTABLE && !NETFX_CORE
using System.IO;
#endif
namespace SharpCompress.Common
{
internal interface IVolume : IDisposable
{
}
}
@@ -0,0 +1,10 @@
namespace SharpCompress.Common
{
internal class IncompleteArchiveException : ArchiveException
{
public IncompleteArchiveException(string message)
: base(message)
{
}
}
}
@@ -0,0 +1,17 @@
using System;
namespace SharpCompress.Common
{
internal class InvalidFormatException : ExtractionException
{
public InvalidFormatException(string message)
: base(message)
{
}
public InvalidFormatException(string message, Exception inner)
: base(message, inner)
{
}
}
}
@@ -0,0 +1,17 @@
using System;
namespace SharpCompress.Common
{
internal class MultiVolumeExtractionException : ExtractionException
{
public MultiVolumeExtractionException(string message)
: base(message)
{
}
public MultiVolumeExtractionException(string message, Exception inner)
: base(message, inner)
{
}
}
}
@@ -0,0 +1,10 @@
namespace SharpCompress.Common
{
internal class MultipartStreamRequiredException : ExtractionException
{
public MultipartStreamRequiredException(string message)
: base(message)
{
}
}
}
@@ -0,0 +1,23 @@
using System;
namespace SharpCompress.Common
{
[Flags]
internal enum Options
{
/// <summary>
/// No options specified
/// </summary>
None = 0,
/// <summary>
/// SharpCompress will keep the supplied streams open
/// </summary>
KeepStreamsOpen = 1,
/// <summary>
/// Look for RarArchive (Check for self-extracting archives or cases where RarArchive isn't at the start of the file)
/// </summary>
LookForHeader = 2,
}
}
@@ -0,0 +1,17 @@
using System;
namespace SharpCompress.Common
{
internal class PasswordProtectedException : ExtractionException
{
public PasswordProtectedException(string message)
: base(message)
{
}
public PasswordProtectedException(string message, Exception inner)
: base(message, inner)
{
}
}
}
@@ -0,0 +1,51 @@
using System.IO;
using SharpCompress.IO;
namespace SharpCompress.Common
{
internal abstract class Volume : IVolume
{
private readonly Stream actualStream;
internal Volume(Stream stream, Options options)
{
actualStream = stream;
Options = options;
}
internal Stream Stream
{
get { return new NonDisposingStream(actualStream); }
}
internal Options Options { get; private set; }
/// <summary>
/// RarArchive is the first volume of a multi-part archive.
/// Only Rar 3.0 format and higher
/// </summary>
public virtual bool IsFirstVolume
{
get { return true; }
}
/// <summary>
/// RarArchive is part of a multi-part archive.
/// </summary>
public virtual bool IsMultiVolume
{
get { return true; }
}
private bool disposed;
public void Dispose()
{
if (!Options.HasFlag(Options.KeepStreamsOpen) && !disposed)
{
actualStream.Dispose();
disposed = true;
}
}
}
}
@@ -0,0 +1,52 @@
using System.IO;
namespace SharpCompress.Common.Zip.Headers
{
internal class DirectoryEndHeader : ZipHeader
{
public DirectoryEndHeader()
: base(ZipHeaderType.DirectoryEnd)
{
}
internal override void Read(BinaryReader reader)
{
VolumeNumber = reader.ReadUInt16();
FirstVolumeWithDirectory = reader.ReadUInt16();
TotalNumberOfEntriesInDisk = reader.ReadUInt16();
TotalNumberOfEntries = reader.ReadUInt16();
DirectorySize = reader.ReadUInt32();
DirectoryStartOffsetRelativeToDisk = reader.ReadUInt32();
CommentLength = reader.ReadUInt16();
Comment = reader.ReadBytes(CommentLength);
}
internal override void Write(BinaryWriter writer)
{
writer.Write(VolumeNumber);
writer.Write(FirstVolumeWithDirectory);
writer.Write(TotalNumberOfEntriesInDisk);
writer.Write(TotalNumberOfEntries);
writer.Write(DirectorySize);
writer.Write(DirectoryStartOffsetRelativeToDisk);
writer.Write(CommentLength);
writer.Write(Comment);
}
public ushort VolumeNumber { get; private set; }
public ushort FirstVolumeWithDirectory { get; private set; }
public ushort TotalNumberOfEntriesInDisk { get; private set; }
public uint DirectorySize { get; private set; }
public uint DirectoryStartOffsetRelativeToDisk { get; private set; }
public ushort CommentLength { get; private set; }
public byte[] Comment { get; private set; }
public ushort TotalNumberOfEntries { get; private set; }
}
}
@@ -0,0 +1,81 @@
using System.IO;
namespace SharpCompress.Common.Zip.Headers
{
internal class DirectoryEntryHeader : ZipFileEntry
{
public DirectoryEntryHeader()
: base(ZipHeaderType.DirectoryEntry)
{
}
internal override void Read(BinaryReader reader)
{
Version = reader.ReadUInt16();
VersionNeededToExtract = reader.ReadUInt16();
Flags = (HeaderFlags) reader.ReadUInt16();
CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16();
LastModifiedTime = reader.ReadUInt16();
LastModifiedDate = reader.ReadUInt16();
Crc = reader.ReadUInt32();
CompressedSize = reader.ReadUInt32();
UncompressedSize = reader.ReadUInt32();
ushort nameLength = reader.ReadUInt16();
ushort extraLength = reader.ReadUInt16();
ushort commentLength = reader.ReadUInt16();
DiskNumberStart = reader.ReadUInt16();
InternalFileAttributes = reader.ReadUInt16();
ExternalFileAttributes = reader.ReadUInt32();
RelativeOffsetOfEntryHeader = reader.ReadUInt32();
byte[] name = reader.ReadBytes(nameLength);
Name = DecodeString(name);
byte[] extra = reader.ReadBytes(extraLength);
byte[] comment = reader.ReadBytes(commentLength);
Comment = DecodeString(comment);
LoadExtra(extra);
}
internal override void Write(BinaryWriter writer)
{
writer.Write(Version);
writer.Write(VersionNeededToExtract);
writer.Write((ushort) Flags);
writer.Write((ushort) CompressionMethod);
writer.Write(LastModifiedTime);
writer.Write(LastModifiedDate);
writer.Write(Crc);
writer.Write(CompressedSize);
writer.Write(UncompressedSize);
byte[] nameBytes = EncodeString(Name);
writer.Write((ushort) nameBytes.Length);
//writer.Write((ushort)Extra.Length);
writer.Write((ushort) 0);
writer.Write((ushort) Comment.Length);
writer.Write(DiskNumberStart);
writer.Write(InternalFileAttributes);
writer.Write(ExternalFileAttributes);
writer.Write(RelativeOffsetOfEntryHeader);
writer.Write(nameBytes);
// writer.Write(Extra);
writer.Write(Comment);
}
internal ushort Version { get; private set; }
public ushort VersionNeededToExtract { get; set; }
public uint RelativeOffsetOfEntryHeader { get; set; }
public uint ExternalFileAttributes { get; set; }
public ushort InternalFileAttributes { get; set; }
public ushort DiskNumberStart { get; set; }
public string Comment { get; private set; }
}
}
@@ -0,0 +1,15 @@
using System;
namespace SharpCompress.Common.Zip.Headers
{
[Flags]
internal enum HeaderFlags : ushort
{
Encrypted = 1, // http://www.pkware.com/documents/casestudies/APPNOTE.TXT
Bit1 = 2,
Bit2 = 4,
UsePostDataDescriptor = 8,
EnhancedDeflate = 16,
UTF8 = 2048
}
}
@@ -0,0 +1,22 @@
using System;
using System.IO;
namespace SharpCompress.Common.Zip.Headers
{
internal class IgnoreHeader : ZipHeader
{
public IgnoreHeader(ZipHeaderType type)
: base(type)
{
}
internal override void Read(BinaryReader reader)
{
}
internal override void Write(BinaryWriter writer)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,66 @@
using System.IO;
namespace SharpCompress.Common.Zip.Headers
{
internal enum ExtraDataType : ushort
{
WinZipAes = 0x9901,
}
internal class ExtraData
{
internal ExtraDataType Type { get; set; }
internal ushort Length { get; set; }
internal byte[] DataBytes { get; set; }
}
internal class LocalEntryHeader : ZipFileEntry
{
public LocalEntryHeader()
: base(ZipHeaderType.LocalEntry)
{
}
internal override void Read(BinaryReader reader)
{
Version = reader.ReadUInt16();
Flags = (HeaderFlags) reader.ReadUInt16();
CompressionMethod = (ZipCompressionMethod) reader.ReadUInt16();
LastModifiedTime = reader.ReadUInt16();
LastModifiedDate = reader.ReadUInt16();
Crc = reader.ReadUInt32();
CompressedSize = reader.ReadUInt32();
UncompressedSize = reader.ReadUInt32();
ushort nameLength = reader.ReadUInt16();
ushort extraLength = reader.ReadUInt16();
byte[] name = reader.ReadBytes(nameLength);
byte[] extra = reader.ReadBytes(extraLength);
Name = DecodeString(name);
LoadExtra(extra);
}
internal override void Write(BinaryWriter writer)
{
writer.Write(Version);
writer.Write((ushort) Flags);
writer.Write((ushort) CompressionMethod);
writer.Write(LastModifiedTime);
writer.Write(LastModifiedDate);
writer.Write(Crc);
writer.Write(CompressedSize);
writer.Write(UncompressedSize);
byte[] nameBytes = EncodeString(Name);
writer.Write((ushort) nameBytes.Length);
writer.Write((ushort) 0);
//if (Extra != null)
//{
// writer.Write(Extra);
//}
writer.Write(nameBytes);
}
internal ushort Version { get; private set; }
}
}
@@ -0,0 +1,22 @@
using System;
namespace SharpCompress.Common.Zip.Headers
{
internal class SplitHeader : ZipHeader
{
public SplitHeader()
: base(ZipHeaderType.Split)
{
}
internal override void Read(System.IO.BinaryReader reader)
{
throw new NotImplementedException();
}
internal override void Write(System.IO.BinaryWriter writer)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace SharpCompress.Common.Zip.Headers
{
internal abstract class ZipFileEntry : ZipHeader
{
protected ZipFileEntry(ZipHeaderType type)
: base(type)
{
Extra = new List<ExtraData>();
}
internal bool IsDirectory
{
get { return Name.EndsWith("/"); }
}
protected string DecodeString(byte[] str)
{
if (FlagUtility.HasFlag(Flags, HeaderFlags.UTF8))
{
return Encoding.UTF8.GetString(str, 0, str.Length);
}
return ArchiveEncoding.Default.GetString(str, 0, str.Length);
}
protected byte[] EncodeString(string str)
{
if (FlagUtility.HasFlag(Flags, HeaderFlags.UTF8))
{
return Encoding.UTF8.GetBytes(str);
}
return ArchiveEncoding.Default.GetBytes(str);
}
internal Stream PackedStream { get; set; }
internal string Name { get; set; }
internal HeaderFlags Flags { get; set; }
internal ZipCompressionMethod CompressionMethod { get; set; }
internal uint CompressedSize { get; set; }
internal long? DataStartPosition { get; set; }
internal uint UncompressedSize { get; set; }
internal List<ExtraData> Extra { get; set; }
internal PkwareTraditionalEncryptionData PkwareTraditionalEncryptionData { get; set; }
#if !PORTABLE && !NETFX_CORE
internal WinzipAesEncryptionData WinzipAesEncryptionData { get; set; }
#endif
internal ushort LastModifiedDate { get; set; }
internal ushort LastModifiedTime { get; set; }
internal uint Crc { get; set; }
protected void LoadExtra(byte[] extra)
{
for (int i = 0; i < extra.Length;)
{
ExtraDataType type = (ExtraDataType) BitConverter.ToUInt16(extra, i);
if (!Enum.IsDefined(typeof (ExtraDataType), type))
{
return;
}
ushort length = BitConverter.ToUInt16(extra, i + 2);
byte[] data = new byte[length];
Buffer.BlockCopy(extra, i + 4, data, 0, length);
Extra.Add(new ExtraData
{
Type = type,
Length = length,
DataBytes = data
});
i += length + 4;
}
}
internal ZipFilePart Part { get; set; }
}
}
@@ -0,0 +1,21 @@
using System.IO;
namespace SharpCompress.Common.Zip.Headers
{
internal abstract class ZipHeader
{
protected ZipHeader(ZipHeaderType type)
{
ZipHeaderType = type;
HasData = true;
}
internal ZipHeaderType ZipHeaderType { get; private set; }
internal abstract void Read(BinaryReader reader);
internal abstract void Write(BinaryWriter writer);
internal bool HasData { get; set; }
}
}
@@ -0,0 +1,11 @@
namespace SharpCompress.Common.Zip.Headers
{
internal enum ZipHeaderType
{
Ignore,
LocalEntry,
DirectoryEntry,
DirectoryEnd,
Split,
}
}
@@ -0,0 +1,120 @@
using System;
using System.IO;
namespace SharpCompress.Common.Zip
{
internal enum CryptoMode
{
Encrypt,
Decrypt
}
internal class PkwareTraditionalCryptoStream : Stream
{
private readonly PkwareTraditionalEncryptionData encryptor;
private readonly CryptoMode mode;
private readonly Stream stream;
private bool isDisposed;
public PkwareTraditionalCryptoStream(Stream stream, PkwareTraditionalEncryptionData encryptor, CryptoMode mode)
{
this.encryptor = encryptor;
this.stream = stream;
this.mode = mode;
}
public override bool CanRead
{
get { return (mode == CryptoMode.Decrypt); }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return (mode == CryptoMode.Encrypt); }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (mode == CryptoMode.Encrypt)
throw new NotSupportedException("This stream does not encrypt via Read()");
if (buffer == null)
throw new ArgumentNullException("buffer");
byte[] temp = new byte[count];
int readBytes = stream.Read(temp, 0, count);
byte[] decrypted = encryptor.Decrypt(temp, readBytes);
Buffer.BlockCopy(decrypted, 0, buffer, offset, readBytes);
return readBytes;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (mode == CryptoMode.Decrypt)
throw new NotSupportedException("This stream does not Decrypt via Write()");
if (count == 0)
{
return;
}
byte[] plaintext = null;
if (offset != 0)
{
plaintext = new byte[count];
Buffer.BlockCopy(buffer, offset, plaintext, 0, count);
}
else
{
plaintext = buffer;
}
byte[] encrypted = encryptor.Encrypt(plaintext, count);
stream.Write(encrypted, 0, encrypted.Length);
}
public override void Flush()
{
//throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
protected override void Dispose(bool disposing)
{
if (isDisposed)
{
return;
}
isDisposed = true;
base.Dispose(disposing);
stream.Dispose();
}
}
}
@@ -0,0 +1,108 @@
using System;
using System.Text;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.Compressor.Deflate;
namespace SharpCompress.Common.Zip
{
internal class PkwareTraditionalEncryptionData
{
private static readonly CRC32 crc32 = new CRC32();
private readonly UInt32[] _Keys = {0x12345678, 0x23456789, 0x34567890};
private PkwareTraditionalEncryptionData(string password)
{
Initialize(password);
}
private byte MagicByte
{
get
{
ushort t = (ushort) ((ushort) (_Keys[2] & 0xFFFF) | 2);
return (byte) ((t*(t ^ 1)) >> 8);
}
}
public static PkwareTraditionalEncryptionData ForRead(string password, ZipFileEntry header,
byte[] encryptionHeader)
{
var encryptor = new PkwareTraditionalEncryptionData(password);
byte[] plainTextHeader = encryptor.Decrypt(encryptionHeader, encryptionHeader.Length);
if (plainTextHeader[11] != (byte) ((header.Crc >> 24) & 0xff))
{
if (!FlagUtility.HasFlag(header.Flags, HeaderFlags.UsePostDataDescriptor))
{
throw new CryptographicException("The password did not match.");
}
if (plainTextHeader[11] != (byte) ((header.LastModifiedTime >> 8) & 0xff))
{
throw new CryptographicException("The password did not match.");
}
}
return encryptor;
}
public byte[] Decrypt(byte[] cipherText, int length)
{
if (length > cipherText.Length)
throw new ArgumentOutOfRangeException("length",
"Bad length during Decryption: the length parameter must be smaller than or equal to the size of the destination array.");
var plainText = new byte[length];
for (int i = 0; i < length; i++)
{
var C = (byte) (cipherText[i] ^ MagicByte);
UpdateKeys(C);
plainText[i] = C;
}
return plainText;
}
public byte[] Encrypt(byte[] plainText, int length)
{
if (plainText == null)
throw new ArgumentNullException("plaintext");
if (length > plainText.Length)
throw new ArgumentOutOfRangeException("length",
"Bad length during Encryption: The length parameter must be smaller than or equal to the size of the destination array.");
var cipherText = new byte[length];
for (int i = 0; i < length; i++)
{
byte C = plainText[i];
cipherText[i] = (byte) (plainText[i] ^ MagicByte);
UpdateKeys(C);
}
return cipherText;
}
private void Initialize(string password)
{
byte[] p = StringToByteArray(password);
for (int i = 0; i < password.Length; i++)
UpdateKeys(p[i]);
}
internal static byte[] StringToByteArray(string value, Encoding encoding)
{
byte[] a = encoding.GetBytes(value);
return a;
}
internal static byte[] StringToByteArray(string value)
{
return StringToByteArray(value, ArchiveEncoding.Password);
}
private void UpdateKeys(byte byteValue)
{
_Keys[0] = (UInt32) crc32.ComputeCrc32((int) _Keys[0], byteValue);
_Keys[1] = _Keys[1] + (byte) _Keys[0];
_Keys[1] = _Keys[1]*0x08088405 + 1;
_Keys[2] = (UInt32) crc32.ComputeCrc32((int) _Keys[2], (byte) (_Keys[1] >> 24));
}
}
}
@@ -0,0 +1,45 @@
using System.IO;
using SharpCompress.Common.Zip.Headers;
namespace SharpCompress.Common.Zip
{
internal class SeekableZipFilePart : ZipFilePart
{
private bool isLocalHeaderLoaded;
private readonly SeekableZipHeaderFactory headerFactory;
internal SeekableZipFilePart(SeekableZipHeaderFactory headerFactory, DirectoryEntryHeader header, Stream stream)
: base(header, stream)
{
this.headerFactory = headerFactory;
}
internal override Stream GetCompressedStream()
{
if (!isLocalHeaderLoaded)
{
LoadLocalHeader();
isLocalHeaderLoaded = true;
}
return base.GetCompressedStream();
}
internal string Comment
{
get { return (Header as DirectoryEntryHeader).Comment; }
}
private void LoadLocalHeader()
{
bool hasData = Header.HasData;
Header = headerFactory.GetLocalHeader(BaseStream, Header as DirectoryEntryHeader);
Header.HasData = hasData;
}
protected override Stream CreateBaseStream()
{
BaseStream.Position = Header.DataStartPosition.Value;
return BaseStream;
}
}
}
@@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.IO;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.IO;
namespace SharpCompress.Common.Zip
{
internal class SeekableZipHeaderFactory : ZipHeaderFactory
{
private const int MAX_ITERATIONS_FOR_DIRECTORY_HEADER = 1000;
internal SeekableZipHeaderFactory(string password)
: base(StreamingMode.Seekable, password)
{
}
internal IEnumerable<DirectoryEntryHeader> ReadSeekableHeader(Stream stream)
{
long offset = 0;
uint signature;
BinaryReader reader = new BinaryReader(stream);
int iterationCount = 0;
do
{
if ((stream.Length + offset) - 4 < 0)
{
throw new ArchiveException("Failed to locate the Zip Header");
}
stream.Seek(offset - 4, SeekOrigin.End);
signature = reader.ReadUInt32();
offset--;
iterationCount++;
if (iterationCount > MAX_ITERATIONS_FOR_DIRECTORY_HEADER)
{
throw new ArchiveException(
"Could not find Zip file Directory at the end of the file. File may be corrupted.");
}
} while (signature != DIRECTORY_END_HEADER_BYTES);
var entry = new DirectoryEndHeader();
entry.Read(reader);
stream.Seek(entry.DirectoryStartOffsetRelativeToDisk, SeekOrigin.Begin);
DirectoryEntryHeader directoryEntryHeader = null;
long position = stream.Position;
while (true)
{
stream.Position = position;
signature = reader.ReadUInt32();
directoryEntryHeader = ReadHeader(signature, reader) as DirectoryEntryHeader;
position = stream.Position;
if (directoryEntryHeader == null)
{
yield break;
}
//entry could be zero bytes so we need to know that.
directoryEntryHeader.HasData = directoryEntryHeader.CompressedSize != 0;
yield return directoryEntryHeader;
}
}
internal LocalEntryHeader GetLocalHeader(Stream stream, DirectoryEntryHeader directoryEntryHeader)
{
stream.Seek(directoryEntryHeader.RelativeOffsetOfEntryHeader, SeekOrigin.Begin);
BinaryReader reader = new BinaryReader(stream);
uint signature = reader.ReadUInt32();
var localEntryHeader = ReadHeader(signature, reader) as LocalEntryHeader;
if (localEntryHeader == null)
{
throw new InvalidOperationException();
}
return localEntryHeader;
}
}
}
@@ -0,0 +1,62 @@
using System;
using System.IO;
using System.IO.Compression;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.IO;
namespace SharpCompress.Common.Zip
{
internal class StreamingZipFilePart : ZipFilePart
{
private Stream decompressionStream;
internal StreamingZipFilePart(ZipFileEntry header, Stream stream)
: base(header, stream)
{
}
protected override Stream CreateBaseStream()
{
return Header.PackedStream;
}
internal override Stream GetCompressedStream()
{
if (!Header.HasData)
{
return Stream.Null;
}
decompressionStream = CreateDecompressionStream(GetCryptoStream(CreateBaseStream()));
if (LeaveStreamOpen)
{
return new NonDisposingStream(decompressionStream);
}
return decompressionStream;
}
internal BinaryReader FixStreamedFileLocation(ref RewindableStream rewindableStream)
{
if (Header.IsDirectory)
{
return new BinaryReader(rewindableStream);
}
if (Header.HasData)
{
if (decompressionStream == null)
{
decompressionStream = GetCompressedStream();
}
decompressionStream.SkipAll();
DeflateStream deflateStream = decompressionStream as DeflateStream;
if (deflateStream != null)
{
rewindableStream.Rewind(deflateStream.BaseStream as MemoryStream);
}
}
var reader = new BinaryReader(rewindableStream);
decompressionStream = null;
return reader;
}
}
}
@@ -0,0 +1,65 @@
using System.Collections.Generic;
using System.IO;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.IO;
namespace SharpCompress.Common.Zip
{
internal class StreamingZipHeaderFactory : ZipHeaderFactory
{
internal StreamingZipHeaderFactory(string password)
: base(StreamingMode.Streaming, password)
{
}
internal IEnumerable<ZipHeader> ReadStreamHeader(Stream stream)
{
RewindableStream rewindableStream;
if (stream is RewindableStream)
{
rewindableStream = stream as RewindableStream;
}
else
{
rewindableStream = new RewindableStream(stream);
}
while (true)
{
ZipHeader header = null;
BinaryReader reader = new BinaryReader(rewindableStream);
if (lastEntryHeader != null &&
FlagUtility.HasFlag(lastEntryHeader.Flags, HeaderFlags.UsePostDataDescriptor))
{
reader = (lastEntryHeader.Part as StreamingZipFilePart).FixStreamedFileLocation(ref rewindableStream);
long pos = rewindableStream.Position;
uint crc = reader.ReadUInt32();
if (crc == POST_DATA_DESCRIPTOR)
{
crc = reader.ReadUInt32();
}
lastEntryHeader.Crc = crc;
lastEntryHeader.CompressedSize = reader.ReadUInt32();
lastEntryHeader.UncompressedSize = reader.ReadUInt32();
lastEntryHeader.DataStartPosition = pos - lastEntryHeader.CompressedSize;
}
lastEntryHeader = null;
uint headerBytes = reader.ReadUInt32();
header = ReadHeader(headerBytes, reader);
//entry could be zero bytes so we need to know that.
if (header.ZipHeaderType == ZipHeaderType.LocalEntry)
{
bool isRecording = rewindableStream.IsRecording;
if (!isRecording)
{
rewindableStream.StartRecording();
}
uint nextHeaderBytes = reader.ReadUInt32();
header.HasData = !IsHeader(nextHeaderBytes);
rewindableStream.Rewind(!isRecording);
}
yield return header;
}
}
}
}
@@ -0,0 +1,180 @@
using System;
using System.IO;
using System.Security.Cryptography;
namespace SharpCompress.Common.Zip
{
internal class WinzipAesCryptoStream : Stream
{
private const int BLOCK_SIZE_IN_BYTES = 16;
private readonly SymmetricAlgorithm cipher;
private readonly byte[] counter = new byte[BLOCK_SIZE_IN_BYTES];
private readonly Stream stream;
private readonly ICryptoTransform transform;
private int nonce = 1;
private byte[] counterOut = new byte[BLOCK_SIZE_IN_BYTES];
private bool isFinalBlock;
private long totalBytesLeftToRead;
private bool isDisposed;
internal WinzipAesCryptoStream(Stream stream, WinzipAesEncryptionData winzipAesEncryptionData, long length)
{
this.stream = stream;
totalBytesLeftToRead = length;
cipher = CreateCipher(winzipAesEncryptionData);
var iv = new byte[BLOCK_SIZE_IN_BYTES];
transform = cipher.CreateEncryptor(winzipAesEncryptionData.KeyBytes, iv);
}
private SymmetricAlgorithm CreateCipher(WinzipAesEncryptionData winzipAesEncryptionData)
{
RijndaelManaged cipher = new RijndaelManaged();
cipher.BlockSize = BLOCK_SIZE_IN_BYTES * 8;
cipher.KeySize = winzipAesEncryptionData.KeyBytes.Length * 8;
cipher.Mode = CipherMode.ECB;
cipher.Padding = PaddingMode.None;
return cipher;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
protected override void Dispose(bool disposing)
{
if (isDisposed)
{
return;
}
isDisposed = true;
if (disposing)
{
//read out last 10 auth bytes
var ten = new byte[10];
stream.Read(ten, 0, 10);
stream.Dispose();
}
}
public override void Flush()
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (totalBytesLeftToRead == 0)
{
return 0;
}
int bytesToRead = count;
if (count > totalBytesLeftToRead)
{
bytesToRead = (int)totalBytesLeftToRead;
}
int read = stream.Read(buffer, offset, bytesToRead);
totalBytesLeftToRead -= read;
ReadTransformBlocks(buffer, offset, read);
return read;
}
private int ReadTransformOneBlock(byte[] buffer, int offset, int last)
{
if (isFinalBlock)
{
throw new InvalidOperationException();
}
int bytesRemaining = last - offset;
int bytesToRead = (bytesRemaining > BLOCK_SIZE_IN_BYTES)
? BLOCK_SIZE_IN_BYTES
: bytesRemaining;
// update the counter
Array.Copy(BitConverter.GetBytes(nonce++), 0, counter, 0, 4);
// Determine if this is the final block
if ((bytesToRead == bytesRemaining) && (totalBytesLeftToRead == 0))
{
counterOut = transform.TransformFinalBlock(counter,
0,
BLOCK_SIZE_IN_BYTES);
isFinalBlock = true;
}
else
{
transform.TransformBlock(counter,
0, // offset
BLOCK_SIZE_IN_BYTES,
counterOut,
0); // offset
}
XorInPlace(buffer, offset, bytesToRead);
return bytesToRead;
}
private void XorInPlace(byte[] buffer, int offset, int count)
{
for (int i = 0; i < count; i++)
{
buffer[offset + i] = (byte)(counterOut[i] ^ buffer[offset + i]);
}
}
private void ReadTransformBlocks(byte[] buffer, int offset, int count)
{
int posn = offset;
int last = count + offset;
while (posn < buffer.Length && posn < last)
{
int n = ReadTransformOneBlock(buffer, posn, last);
posn += n;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,66 @@
using System;
namespace SharpCompress.Common.Zip
{
internal class WinzipAesEncryptionData
{
private const int RFC2898_ITERATIONS = 1000;
private byte[] salt;
private WinzipAesKeySize keySize;
private byte[] passwordVerifyValue;
private string password;
private byte[] generatedVerifyValue;
internal WinzipAesEncryptionData(WinzipAesKeySize keySize, byte[] salt, byte[] passwordVerifyValue,
string password)
{
this.keySize = keySize;
this.salt = salt;
this.passwordVerifyValue = passwordVerifyValue;
this.password = password;
Initialize();
}
internal byte[] IvBytes { get; set; }
internal byte[] KeyBytes { get; set; }
private int KeySizeInBytes
{
get { return KeyLengthInBytes(keySize); }
}
internal static int KeyLengthInBytes(WinzipAesKeySize keySize)
{
switch (keySize)
{
case WinzipAesKeySize.KeySize128:
return 16;
case WinzipAesKeySize.KeySize192:
return 24;
case WinzipAesKeySize.KeySize256:
return 32;
}
throw new InvalidOperationException();
}
private void Initialize()
{
System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 =
new System.Security.Cryptography.Rfc2898DeriveBytes(password, salt, RFC2898_ITERATIONS);
KeyBytes = rfc2898.GetBytes(KeySizeInBytes); // 16 or 24 or 32 ???
IvBytes = rfc2898.GetBytes(KeySizeInBytes);
generatedVerifyValue = rfc2898.GetBytes(2);
short verify = BitConverter.ToInt16(passwordVerifyValue, 0);
if (password != null)
{
short generated = BitConverter.ToInt16(generatedVerifyValue, 0);
if (verify != generated)
throw new InvalidFormatException("bad password");
}
}
}
}
@@ -0,0 +1,9 @@
namespace SharpCompress.Common.Zip
{
internal enum WinzipAesKeySize
{
KeySize128 = 1,
KeySize192 = 2,
KeySize256 = 3,
}
}
@@ -0,0 +1,13 @@
namespace SharpCompress.Common.Zip
{
internal enum ZipCompressionMethod
{
None = 0,
Deflate = 8,
Deflate64 = 9,
BZip2 = 12,
LZMA = 14,
PPMd = 98,
WinzipAes = 0x63 //http://www.winzip.com/aes_info.htm
}
}
@@ -0,0 +1,117 @@
using System;
using System.Collections.Generic;
using SharpCompress.Common.Zip.Headers;
namespace SharpCompress.Common.Zip
{
internal class ZipEntry : Entry
{
private readonly ZipFilePart filePart;
private DateTime? lastModifiedTime;
internal ZipEntry(ZipFilePart filePart)
{
if (filePart != null)
{
this.filePart = filePart;
lastModifiedTime = Utility.DosDateToDateTime(filePart.Header.LastModifiedDate,
filePart.Header.LastModifiedTime);
}
}
public override CompressionType CompressionType
{
get
{
switch (filePart.Header.CompressionMethod)
{
case ZipCompressionMethod.BZip2:
{
return CompressionType.BZip2;
}
case ZipCompressionMethod.Deflate:
{
return CompressionType.Deflate;
}
case ZipCompressionMethod.LZMA:
{
return CompressionType.LZMA;
}
case ZipCompressionMethod.PPMd:
{
return CompressionType.PPMd;
}
case ZipCompressionMethod.None:
{
return CompressionType.None;
}
default:
{
return CompressionType.Unknown;
}
}
}
}
public override uint Crc
{
get { return filePart.Header.Crc; }
}
public override string Key
{
get { return filePart.Header.Name; }
}
public override long CompressedSize
{
get { return filePart.Header.CompressedSize; }
}
public override long Size
{
get { return filePart.Header.UncompressedSize; }
}
public override DateTime? LastModifiedTime
{
get { return lastModifiedTime; }
set { lastModifiedTime = value; }
}
public override DateTime? CreatedTime
{
get { return null; }
}
public override DateTime? LastAccessedTime
{
get { return null; }
}
public override DateTime? ArchivedTime
{
get { return null; }
}
public override bool IsEncrypted
{
get { return FlagUtility.HasFlag(filePart.Header.Flags, HeaderFlags.Encrypted); }
}
public override bool IsDirectory
{
get { return filePart.Header.IsDirectory; }
}
public override bool IsSplit
{
get { return false; }
}
internal override IEnumerable<FilePart> Parts
{
get { return filePart.AsEnumerable<FilePart>(); }
}
}
}
@@ -0,0 +1,184 @@
using System;
using System.IO;
using System.Linq;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.Compressor;
#if BZIP2
using SharpCompress.Compressor.BZip2;
#endif
#if DEFLATE
using SharpCompress.Compressor.Deflate;
#endif
#if LZMA
using SharpCompress.Compressor.LZMA;
#endif
#if PPMd
using SharpCompress.Compressor.PPMd;
#endif
using SharpCompress.IO;
namespace SharpCompress.Common.Zip
{
internal abstract class ZipFilePart : FilePart
{
internal ZipFilePart(ZipFileEntry header, Stream stream)
{
Header = header;
header.Part = this;
this.BaseStream = stream;
}
internal Stream BaseStream { get; private set; }
internal ZipFileEntry Header { get; set; }
internal override string FilePartName
{
get { return Header.Name; }
}
internal override Stream GetCompressedStream()
{
if (!Header.HasData)
{
return Stream.Null;
}
Stream decompressionStream = CreateDecompressionStream(GetCryptoStream(CreateBaseStream()));
if (LeaveStreamOpen)
{
return new NonDisposingStream(decompressionStream);
}
return decompressionStream;
}
internal override Stream GetRawStream()
{
if (!Header.HasData)
{
return Stream.Null;
}
return CreateBaseStream();
}
protected abstract Stream CreateBaseStream();
protected bool LeaveStreamOpen
{
get { return FlagUtility.HasFlag(Header.Flags, HeaderFlags.UsePostDataDescriptor); }
}
protected Stream CreateDecompressionStream(Stream stream)
{
switch (Header.CompressionMethod)
{
case ZipCompressionMethod.None:
{
return stream;
}
case ZipCompressionMethod.Deflate:
{
return new System.IO.Compression.DeflateStream(stream,
System.IO.Compression.CompressionMode.Decompress);
}
#if BZIP2
case ZipCompressionMethod.BZip2:
{
return new BZip2Stream(stream, CompressionMode.Decompress);
}
#endif
#if LZMA
case ZipCompressionMethod.LZMA:
{
if (FlagUtility.HasFlag(Header.Flags, HeaderFlags.Encrypted))
{
throw new NotSupportedException("LZMA with pkware encryption.");
}
var reader = new BinaryReader(stream);
reader.ReadUInt16(); //LZMA version
var props = new byte[reader.ReadUInt16()];
reader.Read(props, 0, props.Length);
return new LzmaStream(props, stream,
Header.CompressedSize > 0 ? Header.CompressedSize - 4 - props.Length : -1,
FlagUtility.HasFlag(Header.Flags, HeaderFlags.Bit1)
? -1
: (long)Header.UncompressedSize);
}
#endif
#if PPMd
case ZipCompressionMethod.PPMd:
{
var props = new byte[2];
stream.Read(props, 0, props.Length);
return new PpmdStream(new PpmdProperties(props), stream, false);
}
#endif
case ZipCompressionMethod.WinzipAes:
{
ExtraData data = Header.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault();
if (data == null)
{
throw new InvalidFormatException("No Winzip AES extra data found.");
}
if (data.Length != 7)
{
throw new InvalidFormatException("Winzip data length is not 7.");
}
ushort method = BitConverter.ToUInt16(data.DataBytes, 0);
if (method != 0x01 && method != 0x02)
{
throw new InvalidFormatException("Unexpected vendor version number for WinZip AES metadata");
}
ushort vendorId = BitConverter.ToUInt16(data.DataBytes, 2);
if (vendorId != 0x4541)
{
throw new InvalidFormatException("Unexpected vendor ID for WinZip AES metadata");
}
Header.CompressionMethod = (ZipCompressionMethod)BitConverter.ToUInt16(data.DataBytes, 5);
return CreateDecompressionStream(stream);
}
default:
{
throw new NotSupportedException("CompressionMethod: " + Header.CompressionMethod);
}
}
}
protected Stream GetCryptoStream(Stream plainStream)
{
if ((Header.CompressedSize == 0)
#if !PORTABLE && !NETFX_CORE
&& ((Header.PkwareTraditionalEncryptionData != null)
|| (Header.WinzipAesEncryptionData != null)))
#else
&& (Header.PkwareTraditionalEncryptionData != null))
#endif
{
throw new NotSupportedException("Cannot encrypt file with unknown size at start.");
}
if ((Header.CompressedSize == 0)
&& FlagUtility.HasFlag(Header.Flags, HeaderFlags.UsePostDataDescriptor))
{
plainStream = new NonDisposingStream(plainStream); //make sure AES doesn't close
}
else
{
plainStream = new ReadOnlySubStream(plainStream, Header.CompressedSize); //make sure AES doesn't close
}
if (Header.PkwareTraditionalEncryptionData != null)
{
return new PkwareTraditionalCryptoStream(plainStream, Header.PkwareTraditionalEncryptionData,
CryptoMode.Decrypt);
}
#if !PORTABLE && !NETFX_CORE
if (Header.WinzipAesEncryptionData != null)
{
//only read 10 less because the last ten are auth bytes
return new WinzipAesCryptoStream(plainStream, Header.WinzipAesEncryptionData, Header.CompressedSize - 10);
}
#endif
return plainStream;
}
}
}
@@ -0,0 +1,187 @@
using System;
using System.IO;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.IO;
#if !PORTABLE
using System.Linq;
#endif
namespace SharpCompress.Common.Zip
{
internal class ZipHeaderFactory
{
internal const uint ENTRY_HEADER_BYTES = 0x04034b50;
internal const uint POST_DATA_DESCRIPTOR = 0x08074b50;
internal const uint DIRECTORY_START_HEADER_BYTES = 0x02014b50;
internal const uint DIRECTORY_END_HEADER_BYTES = 0x06054b50;
internal const uint DIGITAL_SIGNATURE = 0x05054b50;
internal const uint SPLIT_ARCHIVE_HEADER_BYTES = 0x30304b50;
private const uint ZIP64_END_OF_CENTRAL_DIRECTORY = 0x06064b50;
private const uint ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR = 0x07064b50;
protected LocalEntryHeader lastEntryHeader;
private string password;
private StreamingMode mode;
protected ZipHeaderFactory(StreamingMode mode, string password)
{
this.mode = mode;
this.password = password;
}
protected ZipHeader ReadHeader(uint headerBytes, BinaryReader reader)
{
switch (headerBytes)
{
case ENTRY_HEADER_BYTES:
{
var entryHeader = new LocalEntryHeader();
entryHeader.Read(reader);
LoadHeader(entryHeader, reader.BaseStream);
lastEntryHeader = entryHeader;
return entryHeader;
}
case DIRECTORY_START_HEADER_BYTES:
{
var entry = new DirectoryEntryHeader();
entry.Read(reader);
return entry;
}
case POST_DATA_DESCRIPTOR:
{
if (FlagUtility.HasFlag(lastEntryHeader.Flags, HeaderFlags.UsePostDataDescriptor))
{
lastEntryHeader.Crc = reader.ReadUInt32();
lastEntryHeader.CompressedSize = reader.ReadUInt32();
lastEntryHeader.UncompressedSize = reader.ReadUInt32();
}
else
{
reader.ReadUInt32();
reader.ReadUInt32();
reader.ReadUInt32();
}
return null;
}
case DIGITAL_SIGNATURE:
return null;
case DIRECTORY_END_HEADER_BYTES:
{
var entry = new DirectoryEndHeader();
entry.Read(reader);
return entry;
}
case SPLIT_ARCHIVE_HEADER_BYTES:
{
return new SplitHeader();
}
case ZIP64_END_OF_CENTRAL_DIRECTORY:
case ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR:
{
var entry = new IgnoreHeader(ZipHeaderType.Ignore);
entry.Read(reader);
return entry;
}
default:
throw new NotSupportedException("Unknown header: " + headerBytes);
}
}
internal static bool IsHeader(uint headerBytes)
{
switch (headerBytes)
{
case ENTRY_HEADER_BYTES:
case DIRECTORY_START_HEADER_BYTES:
case POST_DATA_DESCRIPTOR:
case DIGITAL_SIGNATURE:
case DIRECTORY_END_HEADER_BYTES:
case SPLIT_ARCHIVE_HEADER_BYTES:
case ZIP64_END_OF_CENTRAL_DIRECTORY:
case ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR:
return true;
default:
return false;
}
}
private void LoadHeader(ZipFileEntry entryHeader, Stream stream)
{
if (FlagUtility.HasFlag(entryHeader.Flags, HeaderFlags.Encrypted))
{
if (!entryHeader.IsDirectory &&
entryHeader.CompressedSize == 0 &&
FlagUtility.HasFlag(entryHeader.Flags, HeaderFlags.UsePostDataDescriptor))
{
throw new NotSupportedException(
"SharpCompress cannot currently read non-seekable Zip Streams with encrypted data that has been written in a non-seekable manner.");
}
if (password == null)
{
throw new CryptographicException("No password supplied for encrypted zip.");
}
if (entryHeader.CompressionMethod != ZipCompressionMethod.WinzipAes)
{
byte[] buffer = new byte[12];
stream.Read(buffer, 0, 12);
entryHeader.PkwareTraditionalEncryptionData = PkwareTraditionalEncryptionData.ForRead(password,
entryHeader,
buffer);
entryHeader.CompressedSize -= 12;
}
else
{
#if PORTABLE || NETFX_CORE
throw new NotSupportedException("Cannot decrypt Winzip AES with Silverlight or WP7.");
#else
var data = entryHeader.Extra.Where(x => x.Type == ExtraDataType.WinZipAes).SingleOrDefault();
WinzipAesKeySize keySize = (WinzipAesKeySize) data.DataBytes[4];
byte[] salt = new byte[WinzipAesEncryptionData.KeyLengthInBytes(keySize)/2];
byte[] passwordVerifyValue = new byte[2];
stream.Read(salt, 0, salt.Length);
stream.Read(passwordVerifyValue, 0, 2);
entryHeader.WinzipAesEncryptionData = new WinzipAesEncryptionData(keySize, salt, passwordVerifyValue,
password);
entryHeader.CompressedSize -= (uint) (salt.Length + 2);
#endif
}
}
if (entryHeader.IsDirectory)
{
return;
}
//if (FlagUtility.HasFlag(entryHeader.Flags, HeaderFlags.UsePostDataDescriptor))
//{
// entryHeader.PackedStream = new ReadOnlySubStream(stream);
//}
//else
//{
switch (mode)
{
case StreamingMode.Seekable:
{
entryHeader.DataStartPosition = stream.Position;
stream.Position += entryHeader.CompressedSize;
}
break;
case StreamingMode.Streaming:
{
entryHeader.PackedStream = stream;
}
break;
default:
{
throw new InvalidFormatException("Invalid StreamingMode");
}
}
//}
}
}
}
@@ -0,0 +1,14 @@
using System.IO;
namespace SharpCompress.Common.Zip
{
internal class ZipVolume : Volume
{
public ZipVolume(Stream stream, Options options)
: base(stream, options)
{
}
public string Comment { get; internal set; }
}
}
@@ -0,0 +1,8 @@
namespace SharpCompress.Compressor
{
internal enum CompressionMode
{
Compress = 0,
Decompress = 1,
}
}
@@ -0,0 +1,288 @@
// Crc32.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2006-2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2010-January-16 13:16:27>
//
// ------------------------------------------------------------------
//
// Implements the CRC algorithm, which is used in zip files. The zip format calls for
// the zipfile to contain a CRC for the unencrypted byte stream of each file.
//
// It is based on example source code published at
// http://www.vbaccelerator.com/home/net/code/libraries/CRC32/Crc32_zip_CRC32_CRC32_cs.asp
//
// This implementation adds a tweak of that code for use within zip creation. While
// computing the CRC we also compress the byte stream, in the same read loop. This
// avoids the need to read through the uncompressed stream twice - once to compute CRC
// and another time to compress.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace SharpCompress.Compressor.Deflate
{
/// <summary>
/// Calculates a 32bit Cyclic Redundancy Checksum (CRC) using the same polynomial
/// used by Zip. This type is used internally by DotNetZip; it is generally not used
/// directly by applications wishing to create, read, or manipulate zip archive
/// files.
/// </summary>
internal class CRC32
{
private const int BUFFER_SIZE = 8192;
private static readonly UInt32[] crc32Table;
private UInt32 runningCrc32Result = 0xFFFFFFFF;
private Int64 totalBytesRead;
static CRC32()
{
unchecked
{
// PKZip specifies CRC32 with a polynomial of 0xEDB88320;
// This is also the CRC-32 polynomial used bby Ethernet, FDDI,
// bzip2, gzip, and others.
// Often the polynomial is shown reversed as 0x04C11DB7.
// For more details, see http://en.wikipedia.org/wiki/Cyclic_redundancy_check
UInt32 dwPolynomial = 0xEDB88320;
UInt32 i, j;
crc32Table = new UInt32[256];
UInt32 dwCrc;
for (i = 0; i < 256; i++)
{
dwCrc = i;
for (j = 8; j > 0; j--)
{
if ((dwCrc & 1) == 1)
{
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
}
else
{
dwCrc >>= 1;
}
}
crc32Table[i] = dwCrc;
}
}
}
/// <summary>
/// indicates the total number of bytes read on the CRC stream.
/// This is used when writing the ZipDirEntry when compressing files.
/// </summary>
public Int64 TotalBytesRead
{
get { return totalBytesRead; }
}
/// <summary>
/// Indicates the current CRC for all blocks slurped in.
/// </summary>
public Int32 Crc32Result
{
get
{
// return one's complement of the running result
return unchecked((Int32) (~runningCrc32Result));
}
}
/// <summary>
/// Returns the CRC32 for the specified stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32(Stream input)
{
return GetCrc32AndCopy(input, null);
}
/// <summary>
/// Returns the CRC32 for the specified stream, and writes the input into the
/// output stream.
/// </summary>
/// <param name="input">The stream over which to calculate the CRC32</param>
/// <param name="output">The stream into which to deflate the input</param>
/// <returns>the CRC32 calculation</returns>
public Int32 GetCrc32AndCopy(Stream input, Stream output)
{
if (input == null)
throw new ZlibException("The input stream must not be null.");
unchecked
{
//UInt32 crc32Result;
//crc32Result = 0xFFFFFFFF;
var buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
totalBytesRead = 0;
int count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
totalBytesRead += count;
while (count > 0)
{
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
totalBytesRead += count;
}
return (Int32) (~runningCrc32Result);
}
}
/// <summary>
/// Get the CRC32 for the given (word,byte) combo. This is a computation
/// defined by PKzip.
/// </summary>
/// <param name="W">The word to start with.</param>
/// <param name="B">The byte to combine it with.</param>
/// <returns>The CRC-ized result.</returns>
public Int32 ComputeCrc32(Int32 W, byte B)
{
return _InternalComputeCrc32((UInt32) W, B);
}
internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
{
return (Int32) (crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
/// <summary>
/// Update the value for the running CRC32 using the given block of bytes.
/// This is useful when using the CRC32() class in a Stream.
/// </summary>
/// <param name="block">block of bytes to slurp</param>
/// <param name="offset">starting point in the block</param>
/// <param name="count">how many bytes within the block to slurp</param>
public void SlurpBlock(byte[] block, int offset, int count)
{
if (block == null)
throw new ZlibException("The data buffer must not be null.");
for (int i = 0; i < count; i++)
{
int x = offset + i;
runningCrc32Result = ((runningCrc32Result) >> 8) ^
crc32Table[(block[x]) ^ ((runningCrc32Result) & 0x000000FF)];
}
totalBytesRead += count;
}
// pre-initialize the crc table for speed of lookup.
private uint gf2_matrix_times(uint[] matrix, uint vec)
{
uint sum = 0;
int i = 0;
while (vec != 0)
{
if ((vec & 0x01) == 0x01)
sum ^= matrix[i];
vec >>= 1;
i++;
}
return sum;
}
private void gf2_matrix_square(uint[] square, uint[] mat)
{
for (int i = 0; i < 32; i++)
square[i] = gf2_matrix_times(mat, mat[i]);
}
/// <summary>
/// Combines the given CRC32 value with the current running total.
/// </summary>
/// <remarks>
/// This is useful when using a divide-and-conquer approach to calculating a CRC.
/// Multiple threads can each calculate a CRC32 on a segment of the data, and then
/// combine the individual CRC32 values at the end.
/// </remarks>
/// <param name="crc">the crc value to be combined with this one</param>
/// <param name="length">the length of data the CRC value was calculated on</param>
public void Combine(int crc, int length)
{
var even = new uint[32]; // even-power-of-two zeros operator
var odd = new uint[32]; // odd-power-of-two zeros operator
if (length == 0)
return;
uint crc1 = ~runningCrc32Result;
var crc2 = (uint) crc;
// put operator for one zero bit in odd
odd[0] = 0xEDB88320; // the CRC-32 polynomial
uint row = 1;
for (int i = 1; i < 32; i++)
{
odd[i] = row;
row <<= 1;
}
// put operator for two zero bits in even
gf2_matrix_square(even, odd);
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
var len2 = (uint) length;
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
do
{
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
if ((len2 & 1) == 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
if (len2 == 0)
break;
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
if ((len2 & 1) == 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
} while (len2 != 0);
crc1 ^= crc2;
runningCrc32Result = ~crc1;
//return (int) crc1;
return;
}
// private member vars
}
}
@@ -0,0 +1,279 @@
// Zlib.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009 Dino Chiesa and Microsoft Corporation.
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2009-November-07 05:26:55>
//
// ------------------------------------------------------------------
//
// This module defines classes for ZLIB compression and
// decompression. This code is derived from the jzlib implementation of
// zlib, but significantly modified. The object model is not the same,
// and many of the behaviors are new or different. Nonetheless, in
// keeping with the license for jzlib, the copyright to that code is
// included below.
//
// ------------------------------------------------------------------
//
// Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the distribution.
//
// 3. The names of the authors may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
// INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// -----------------------------------------------------------------------
//
// This program is based on zlib-1.1.3; credit to authors
// Jean-loup Gailly([email protected]) and Mark Adler([email protected])
// and contributors of zlib.
//
// -----------------------------------------------------------------------
namespace SharpCompress.Compressor.Deflate
{
/// <summary>
/// The compression level to be used when using a DeflateStream or ZlibStream with CompressionMode.Compress.
/// </summary>
internal enum CompressionLevel
{
/// <summary>
/// None means that the data will be simply stored, with no change at all.
/// If you are producing ZIPs for use on Mac OSX, be aware that archives produced with CompressionLevel.None
/// cannot be opened with the default zip reader. Use a different CompressionLevel.
/// </summary>
None = 0,
/// <summary>
/// Same as None.
/// </summary>
Level0 = 0,
/// <summary>
/// The fastest but least effective compression.
/// </summary>
BestSpeed = 1,
/// <summary>
/// A synonym for BestSpeed.
/// </summary>
Level1 = 1,
/// <summary>
/// A little slower, but better, than level 1.
/// </summary>
Level2 = 2,
/// <summary>
/// A little slower, but better, than level 2.
/// </summary>
Level3 = 3,
/// <summary>
/// A little slower, but better, than level 3.
/// </summary>
Level4 = 4,
/// <summary>
/// A little slower than level 4, but with better compression.
/// </summary>
Level5 = 5,
/// <summary>
/// The default compression level, with a good balance of speed and compression efficiency.
/// </summary>
Default = 6,
/// <summary>
/// A synonym for Default.
/// </summary>
Level6 = 6,
/// <summary>
/// Pretty good compression!
/// </summary>
Level7 = 7,
/// <summary>
/// Better compression than Level7!
/// </summary>
Level8 = 8,
/// <summary>
/// The "best" compression, where best means greatest reduction in size of the input data stream.
/// This is also the slowest compression.
/// </summary>
BestCompression = 9,
/// <summary>
/// A synonym for BestCompression.
/// </summary>
Level9 = 9,
}
/// <summary>
/// Describes options for how the compression algorithm is executed. Different strategies
/// work better on different sorts of data. The strategy parameter can affect the compression
/// ratio and the speed of compression but not the correctness of the compresssion.
/// </summary>
internal enum CompressionStrategy
{
/// <summary>
/// The default strategy is probably the best for normal data.
/// </summary>
Default = 0,
/// <summary>
/// The <c>Filtered</c> strategy is intended to be used most effectively with data produced by a
/// filter or predictor. By this definition, filtered data consists mostly of small
/// values with a somewhat random distribution. In this case, the compression algorithm
/// is tuned to compress them better. The effect of <c>Filtered</c> is to force more Huffman
/// coding and less string matching; it is a half-step between <c>Default</c> and <c>HuffmanOnly</c>.
/// </summary>
Filtered = 1,
/// <summary>
/// Using <c>HuffmanOnly</c> will force the compressor to do Huffman encoding only, with no
/// string matching.
/// </summary>
HuffmanOnly = 2,
}
/// <summary>
/// A general purpose exception class for exceptions in the Zlib library.
/// </summary>
internal class ZlibException : System.Exception
{
/// <summary>
/// The ZlibException class captures exception information generated
/// by the Zlib library.
/// </summary>
public ZlibException()
: base()
{
}
/// <summary>
/// This ctor collects a message attached to the exception.
/// </summary>
/// <param name="s"></param>
public ZlibException(System.String s)
: base(s)
{
}
}
/// <summary>
/// Computes an Adler-32 checksum.
/// </summary>
/// <remarks>
/// The Adler checksum is similar to a CRC checksum, but faster to compute, though less
/// reliable. It is used in producing RFC1950 compressed streams. The Adler checksum
/// is a required part of the "ZLIB" standard. Applications will almost never need to
/// use this class directly.
/// </remarks>
internal sealed class Adler
{
// largest prime smaller than 65536
private static readonly int BASE = 65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
private static readonly int NMAX = 5552;
internal static uint Adler32(uint adler, byte[] buf, int index, int len)
{
if (buf == null)
return 1;
int s1 = (int) (adler & 0xffff);
int s2 = (int) ((adler >> 16) & 0xffff);
while (len > 0)
{
int k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16)
{
//s1 += (buf[index++] & 0xff); s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
s1 += buf[index++];
s2 += s1;
k -= 16;
}
if (k != 0)
{
do
{
s1 += buf[index++];
s2 += s1;
} while (--k != 0);
}
s1 %= BASE;
s2 %= BASE;
}
return (uint) ((s2 << 16) | s1);
}
}
}
@@ -0,0 +1,15 @@
using System;
namespace SharpCompress
{
internal static class EnumExtensions
{
public static bool HasFlag(this Enum enumRef, Enum flag)
{
long value = Convert.ToInt64(enumRef);
long flagVal = Convert.ToInt64(flag);
return (value & flagVal) == flagVal;
}
}
}
@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace SharpCompress.IO
{
internal class ReadOnlyAppendingStream : Stream
{
private readonly Queue<Stream> streams;
private Stream current;
public ReadOnlyAppendingStream(IEnumerable<Stream> streams)
{
this.streams = new Queue<Stream>(streams);
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
throw new NotImplementedException();
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (current == null && streams.Count == 0)
{
return -1;
}
if (current == null)
{
current = streams.Dequeue();
}
int totalRead = 0;
while (totalRead < count)
{
int read = current.Read(buffer, offset + totalRead, count - totalRead);
if (read <= 0)
{
if (streams.Count == 0)
{
return totalRead;
}
else
{
current = streams.Dequeue();
}
}
totalRead += read;
}
return totalRead;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,68 @@
using System;
using System.IO;
namespace SharpCompress.IO
{
internal class CountingWritableSubStream : Stream
{
private Stream writableStream;
internal CountingWritableSubStream(Stream stream)
{
writableStream = stream;
}
public uint Count { get; private set; }
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override void Flush()
{
}
public override long Length
{
get { throw new NotImplementedException(); }
}
public override long Position
{
get { throw new NotImplementedException(); }
set { throw new NotImplementedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
writableStream.Write(buffer, offset, count);
Count += (uint) count;
}
}
}
@@ -0,0 +1,81 @@
using System.IO;
using SharpCompress.Common;
namespace SharpCompress.IO
{
internal class ListeningStream : Stream
{
private long currentEntryTotalReadBytes;
private IExtractionListener listener;
public ListeningStream(IExtractionListener listener, Stream stream)
{
Stream = stream;
this.listener = listener;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Stream.Dispose();
}
}
public Stream Stream { get; private set; }
public override bool CanRead
{
get { return Stream.CanRead; }
}
public override bool CanSeek
{
get { return Stream.CanSeek; }
}
public override bool CanWrite
{
get { return Stream.CanWrite; }
}
public override void Flush()
{
Stream.Flush();
}
public override long Length
{
get { return Stream.Length; }
}
public override long Position
{
get { return Stream.Position; }
set { Stream.Position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{
int read = Stream.Read(buffer, offset, count);
currentEntryTotalReadBytes += read;
listener.FireCompressedBytesRead(currentEntryTotalReadBytes, currentEntryTotalReadBytes);
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
return Stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
Stream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
Stream.Write(buffer, offset, count);
}
}
}
@@ -0,0 +1,136 @@
using System;
using System.IO;
using System.Linq;
namespace SharpCompress.IO
{
internal class MarkingBinaryReader : BinaryReader
{
public MarkingBinaryReader(Stream stream)
: base(stream)
{
}
public long CurrentReadByteCount { get; private set; }
public void Mark()
{
CurrentReadByteCount = 0;
}
public override int Read()
{
throw new NotImplementedException();
}
public override int Read(byte[] buffer, int index, int count)
{
throw new NotImplementedException();
}
public override int Read(char[] buffer, int index, int count)
{
throw new NotImplementedException();
}
public override bool ReadBoolean()
{
return BitConverter.ToBoolean(ReadBytes(1), 0);
}
public override byte ReadByte()
{
return ReadBytes(1).Single();
}
public override byte[] ReadBytes(int count)
{
CurrentReadByteCount += count;
var bytes = base.ReadBytes(count);
if (bytes.Length != count)
{
throw new EndOfStreamException(string.Format("Could not read the requested amount of bytes. End of stream reached. Requested: {0} Read: {1}", count, bytes.Length));
}
return bytes;
}
public override char ReadChar()
{
throw new NotImplementedException();
}
public override char[] ReadChars(int count)
{
throw new NotImplementedException();
}
#if !PORTABLE
public override decimal ReadDecimal()
{
return ByteArrayToDecimal(ReadBytes(16), 0);
}
private decimal ByteArrayToDecimal(byte[] src, int offset)
{
//http://stackoverflow.com/a/16984356/385387
var i1 = BitConverter.ToInt32(src, offset);
var i2 = BitConverter.ToInt32(src, offset + 4);
var i3 = BitConverter.ToInt32(src, offset + 8);
var i4 = BitConverter.ToInt32(src, offset + 12);
return new decimal(new[] { i1, i2, i3, i4 });
}
#endif
public override double ReadDouble()
{
return BitConverter.ToDouble(ReadBytes(8), 0);
}
public override short ReadInt16()
{
return BitConverter.ToInt16(ReadBytes(2), 0);
}
public override int ReadInt32()
{
return BitConverter.ToInt32(ReadBytes(4), 0);
}
public override long ReadInt64()
{
return BitConverter.ToInt64(ReadBytes(8), 0);
}
public override sbyte ReadSByte()
{
return (sbyte)ReadByte();
}
public override float ReadSingle()
{
return BitConverter.ToSingle(ReadBytes(4), 0);
}
public override string ReadString()
{
throw new NotImplementedException();
}
public override ushort ReadUInt16()
{
return BitConverter.ToUInt16(ReadBytes(2), 0);
}
public override uint ReadUInt32()
{
return BitConverter.ToUInt32(ReadBytes(4), 0);
}
public override ulong ReadUInt64()
{
return BitConverter.ToUInt64(ReadBytes(8), 0);
}
}
}
@@ -0,0 +1,70 @@
using System.IO;
namespace SharpCompress.IO
{
internal class NonDisposingStream : Stream
{
public NonDisposingStream(Stream stream)
{
Stream = stream;
}
protected override void Dispose(bool disposing)
{
//don't dispose anything
}
public Stream Stream { get; private set; }
public override bool CanRead
{
get { return Stream.CanRead; }
}
public override bool CanSeek
{
get { return Stream.CanSeek; }
}
public override bool CanWrite
{
get { return Stream.CanWrite; }
}
public override void Flush()
{
Stream.Flush();
}
public override long Length
{
get { return Stream.Length; }
}
public override long Position
{
get { return Stream.Position; }
set { Stream.Position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{
return Stream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return Stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
Stream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
Stream.Write(buffer, offset, count);
}
}
}
@@ -0,0 +1,94 @@
using System.IO;
namespace SharpCompress.IO
{
internal class ReadOnlySubStream : Stream
{
public ReadOnlySubStream(Stream stream, long bytesToRead)
: this(stream, null, bytesToRead)
{
}
public ReadOnlySubStream(Stream stream, long? origin, long bytesToRead)
{
Stream = stream;
if (origin != null)
{
stream.Position = origin.Value;
}
BytesLeftToRead = bytesToRead;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
//Stream.Dispose();
}
}
private long BytesLeftToRead { get; set; }
public Stream Stream { get; private set; }
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
throw new System.NotImplementedException();
}
public override long Length
{
get { throw new System.NotImplementedException(); }
}
public override long Position
{
get { throw new System.NotImplementedException(); }
set { throw new System.NotImplementedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (BytesLeftToRead < count)
{
count = (int)BytesLeftToRead;
}
int read = Stream.Read(buffer, offset, count);
if (read > 0)
{
BytesLeftToRead -= read;
}
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new System.NotImplementedException();
}
public override void SetLength(long value)
{
throw new System.NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new System.NotImplementedException();
}
}
}
@@ -0,0 +1,163 @@
using System.IO;
namespace SharpCompress.IO
{
internal class RewindableStream : Stream
{
private readonly Stream stream;
private MemoryStream bufferStream = new MemoryStream();
private bool isRewound;
private bool isDisposed;
public RewindableStream(Stream stream)
{
this.stream = stream;
}
internal bool IsRecording { get; private set; }
protected override void Dispose(bool disposing)
{
if (isDisposed)
{
return;
}
isDisposed = true;
base.Dispose(disposing);
if (disposing)
{
stream.Dispose();
}
}
public void Rewind(bool stopRecording)
{
isRewound = true;
IsRecording = !stopRecording;
bufferStream.Position = 0;
}
public void Rewind(MemoryStream buffer)
{
if (bufferStream.Position >= buffer.Length)
{
bufferStream.Position -= buffer.Length;
}
else
{
bufferStream.TransferTo(buffer);
bufferStream = buffer;
bufferStream.Position = 0;
}
isRewound = true;
}
public void StartRecording()
{
//if (isRewound && bufferStream.Position != 0)
// throw new System.NotImplementedException();
if (bufferStream.Position != 0)
{
byte[] data = bufferStream.ToArray();
long position = bufferStream.Position;
bufferStream.SetLength(0);
bufferStream.Write(data, (int)position, data.Length - (int)position);
bufferStream.Position = 0;
}
IsRecording = true;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
throw new System.NotImplementedException();
}
public override long Length
{
get { throw new System.NotImplementedException(); }
}
public override long Position
{
get { return stream.Position + bufferStream.Position - bufferStream.Length; }
set
{
if (!isRewound)
{
stream.Position = value;
}
else if (value < stream.Position - bufferStream.Length || value >= stream.Position)
{
stream.Position = value;
isRewound = false;
bufferStream.SetLength(0);
}
else
{
bufferStream.Position = value - stream.Position + bufferStream.Length;
}
}
}
public override int Read(byte[] buffer, int offset, int count)
{
int read;
if (isRewound && bufferStream.Position != bufferStream.Length)
{
read = bufferStream.Read(buffer, offset, count);
if (read < count)
{
int tempRead = stream.Read(buffer, offset + read, count - read);
if (IsRecording)
{
bufferStream.Write(buffer, offset + read, tempRead);
}
read += tempRead;
}
if (bufferStream.Position == bufferStream.Length && !IsRecording)
{
isRewound = false;
bufferStream.SetLength(0);
}
return read;
}
read = stream.Read(buffer, offset, count);
if (IsRecording)
{
bufferStream.Write(buffer, offset, read);
}
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new System.NotImplementedException();
}
public override void SetLength(long value)
{
throw new System.NotImplementedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new System.NotImplementedException();
}
}
}
@@ -0,0 +1,8 @@
namespace SharpCompress.IO
{
internal enum StreamingMode
{
Streaming,
Seekable,
}
}
@@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
namespace SharpCompress
{
internal class LazyReadOnlyCollection<T> : ICollection<T>
{
private readonly List<T> backing = new List<T>();
private readonly IEnumerator<T> source;
private bool fullyLoaded;
public LazyReadOnlyCollection(IEnumerable<T> source)
{
this.source = source.GetEnumerator();
}
private class LazyLoader : IEnumerator<T>
{
private readonly LazyReadOnlyCollection<T> lazyReadOnlyCollection;
private bool disposed;
private int index = -1;
internal LazyLoader(LazyReadOnlyCollection<T> lazyReadOnlyCollection)
{
this.lazyReadOnlyCollection = lazyReadOnlyCollection;
}
#region IEnumerator<T> Members
public T Current
{
get { return lazyReadOnlyCollection.backing[index]; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (!disposed)
{
disposed = true;
}
}
#endregion
#region IEnumerator Members
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (index + 1 < lazyReadOnlyCollection.backing.Count)
{
index++;
return true;
}
if (!lazyReadOnlyCollection.fullyLoaded && lazyReadOnlyCollection.source.MoveNext())
{
lazyReadOnlyCollection.backing.Add(lazyReadOnlyCollection.source.Current);
index++;
return true;
}
lazyReadOnlyCollection.fullyLoaded = true;
return false;
}
public void Reset()
{
throw new NotImplementedException();
}
#endregion
}
internal void EnsureFullyLoaded()
{
if (!fullyLoaded)
{
this.ForEach(x => { });
fullyLoaded = true;
}
}
internal IEnumerable<T> GetLoaded()
{
return backing;
}
#region ICollection<T> Members
public void Add(T item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(T item)
{
EnsureFullyLoaded();
return backing.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
EnsureFullyLoaded();
backing.CopyTo(array, arrayIndex);
}
public int Count
{
get
{
EnsureFullyLoaded();
return backing.Count;
}
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
#endregion
#region IEnumerable<T> Members
//TODO check for concurrent access
public IEnumerator<T> GetEnumerator()
{
return new LazyLoader(this);
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
namespace SharpCompress
{
internal class ReadOnlyCollection<T> : ICollection<T>
{
private ICollection<T> collection;
public ReadOnlyCollection(ICollection<T> collection)
{
this.collection = collection;
}
public void Add(T item)
{
throw new NotImplementedException();
}
public void Clear()
{
throw new NotImplementedException();
}
public bool Contains(T item)
{
return collection.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return collection.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(T item)
{
throw new NotImplementedException();
}
public IEnumerator<T> GetEnumerator()
{
return collection.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,226 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Common;
#if PORTABLE
using SharpCompress.Common.Rar.Headers;
#endif
namespace SharpCompress.Reader
{
/// <summary>
/// A generic push reader that reads unseekable comrpessed streams.
/// </summary>
internal abstract class AbstractReader<TEntry, TVolume> : IReader, IExtractionListener
where TEntry : Entry
where TVolume : Volume
{
private bool completed;
private IEnumerator<TEntry> entriesForCurrentReadStream;
private bool wroteCurrentEntry;
public event EventHandler<CompressedBytesReadEventArgs> CompressedBytesRead;
public event EventHandler<FilePartExtractionBeginEventArgs> FilePartExtractionBegin;
internal AbstractReader(Options options, ArchiveType archiveType)
{
ArchiveType = archiveType;
Options = options;
}
internal Options Options { get; private set; }
public ArchiveType ArchiveType { get; private set; }
/// <summary>
/// Current volume that the current entry resides in
/// </summary>
public abstract TVolume Volume { get; }
/// <summary>
/// Current file entry
/// </summary>
public TEntry Entry
{
get { return entriesForCurrentReadStream.Current; }
}
#region IDisposable Members
public void Dispose()
{
if (entriesForCurrentReadStream != null)
{
entriesForCurrentReadStream.Dispose();
}
Volume.Dispose();
}
#endregion
public bool MoveToNextEntry()
{
if (completed)
{
return false;
}
if (entriesForCurrentReadStream == null)
{
return LoadStreamForReading(RequestInitialStream());
}
if (!wroteCurrentEntry)
{
SkipEntry();
}
wroteCurrentEntry = false;
if (NextEntryForCurrentStream())
{
return true;
}
completed = true;
return false;
}
internal bool LoadStreamForReading(Stream stream)
{
if (entriesForCurrentReadStream != null)
{
entriesForCurrentReadStream.Dispose();
}
if ((stream == null) || (!stream.CanRead))
{
throw new MultipartStreamRequiredException("File is split into multiple archives: '"
+ Entry.Key +
"'. A new readable stream is required. Use Cancel if it was intended.");
}
entriesForCurrentReadStream = GetEntries(stream).GetEnumerator();
if (entriesForCurrentReadStream.MoveNext())
{
return true;
}
return false;
}
internal virtual Stream RequestInitialStream()
{
return Volume.Stream;
}
internal virtual bool NextEntryForCurrentStream()
{
return entriesForCurrentReadStream.MoveNext();
}
internal abstract IEnumerable<TEntry> GetEntries(Stream stream);
#region Entry Skip/Write
private void SkipEntry()
{
if (!Entry.IsDirectory)
{
Skip();
}
}
private readonly byte[] skipBuffer = new byte[4096];
private void Skip()
{
if (!Entry.IsSolid)
{
var rawStream = Entry.Parts.First().GetRawStream();
if (rawStream != null)
{
var bytesToAdvance = Entry.CompressedSize;
for (var i = 0; i < bytesToAdvance / skipBuffer.Length; i++)
{
rawStream.Read(skipBuffer, 0, skipBuffer.Length);
}
rawStream.Read(skipBuffer, 0, (int)(bytesToAdvance % skipBuffer.Length));
return;
}
}
using (var s = OpenEntryStream())
{
while (s.Read(skipBuffer, 0, skipBuffer.Length) > 0)
{
}
}
}
public void WriteEntryTo(Stream writableStream)
{
if (wroteCurrentEntry)
{
throw new ArgumentException("WriteEntryTo or OpenEntryStream can only be called once.");
}
if ((writableStream == null) || (!writableStream.CanWrite))
{
throw new ArgumentNullException(
"A writable Stream was required. Use Cancel if that was intended.");
}
Write(writableStream);
wroteCurrentEntry = true;
}
internal void Write(Stream writeStream)
{
using (Stream s = OpenEntryStream())
{
s.TransferTo(writeStream);
}
}
public EntryStream OpenEntryStream()
{
if (wroteCurrentEntry)
{
throw new ArgumentException("WriteEntryTo or OpenEntryStream can only be called once.");
}
var stream = GetEntryStream();
wroteCurrentEntry = true;
return stream;
}
protected virtual EntryStream GetEntryStream()
{
return new EntryStream(Entry.Parts.First().GetCompressedStream());
}
#endregion
IEntry IReader.Entry
{
get { return Entry; }
}
void IExtractionListener.FireCompressedBytesRead(long currentPartCompressedBytes, long compressedReadBytes)
{
if (CompressedBytesRead != null)
{
CompressedBytesRead(this, new CompressedBytesReadEventArgs()
{
CurrentFilePartCompressedBytesRead = currentPartCompressedBytes,
CompressedBytesRead = compressedReadBytes
});
}
}
void IExtractionListener.FireFilePartExtractionBegin(string name, long size, long compressedSize)
{
if (FilePartExtractionBegin != null)
{
FilePartExtractionBegin(this, new FilePartExtractionBeginEventArgs()
{
CompressedSize = compressedSize,
Size = size,
Name = name,
});
}
}
}
}
@@ -0,0 +1,95 @@
using System.IO;
using SharpCompress.Common;
namespace SharpCompress.Reader
{
internal static class IReaderExtensions
{
#if !PORTABLE && !NETFX_CORE
public static void WriteEntryTo(this IReader reader, string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Create, FileAccess.Write))
{
reader.WriteEntryTo(stream);
}
}
public static void WriteEntryTo(this IReader reader, FileInfo filePath)
{
using (Stream stream = filePath.Open(FileMode.Create))
{
reader.WriteEntryTo(stream);
}
}
/// <summary>
/// Extract all remaining unread entries to specific directory, retaining filename
/// </summary>
public static void WriteAllToDirectory(this IReader reader, string destinationDirectory,
ExtractOptions options = ExtractOptions.Overwrite)
{
while (reader.MoveToNextEntry())
{
reader.WriteEntryToDirectory(destinationDirectory, options);
}
}
/// <summary>
/// Extract to specific directory, retaining filename
/// </summary>
public static void WriteEntryToDirectory(this IReader reader, string destinationDirectory,
ExtractOptions options = ExtractOptions.Overwrite)
{
string destinationFileName = string.Empty;
string file = Path.GetFileName(reader.Entry.Key);
if (options.HasFlag(ExtractOptions.ExtractFullPath))
{
string folder = Path.GetDirectoryName(reader.Entry.Key);
string destdir = Path.Combine(destinationDirectory, folder);
if (!Directory.Exists(destdir))
{
Directory.CreateDirectory(destdir);
}
destinationFileName = Path.Combine(destdir, file);
}
else
{
destinationFileName = Path.Combine(destinationDirectory, file);
}
if (!reader.Entry.IsDirectory)
{
reader.WriteEntryToFile(destinationFileName, options);
}
else if (options.HasFlag(ExtractOptions.ExtractFullPath) && !Directory.Exists(destinationFileName))
{
Directory.CreateDirectory(destinationFileName);
}
}
/// <summary>
/// Extract to specific file
/// </summary>
public static void WriteEntryToFile(this IReader reader, string destinationFileName,
ExtractOptions options = ExtractOptions.Overwrite)
{
FileMode fm = FileMode.Create;
if (!options.HasFlag(ExtractOptions.Overwrite))
{
fm = FileMode.CreateNew;
}
using (FileStream fs = File.Open(destinationFileName, fm))
{
reader.WriteEntryTo(fs);
//using (Stream s = reader.OpenEntryStream())
//{
// s.TransferTo(fs);
//}
}
}
#endif
}
}
@@ -0,0 +1,34 @@
using System;
using System.IO;
using SharpCompress.Common;
namespace SharpCompress.Reader
{
internal interface IReader : IDisposable
{
event EventHandler<CompressedBytesReadEventArgs> CompressedBytesRead;
event EventHandler<FilePartExtractionBeginEventArgs> FilePartExtractionBegin;
ArchiveType ArchiveType { get; }
IEntry Entry { get; }
/// <summary>
/// Decompresses the current entry to the stream. This cannot be called twice for the current entry.
/// </summary>
/// <param name="writableStream"></param>
void WriteEntryTo(Stream writableStream);
/// <summary>
/// Moves to the next entry by reading more data from the underlying stream. This skips if data has not been read.
/// </summary>
/// <returns></returns>
bool MoveToNextEntry();
/// <summary>
/// Opens the current entry as a stream that will decompress as it is read.
/// Read the entire stream or use SkipEntry on EntryStream.
/// </summary>
EntryStream OpenEntryStream();
}
}
@@ -0,0 +1,106 @@
using System;
using System.IO;
#if GZIP
using SharpCompress.Archive.GZip;
#endif
#if RAR
using SharpCompress.Archive.Rar;
#endif
#if TAR
using SharpCompress.Archive.Tar;
#endif
using SharpCompress.Archive.Zip;
using SharpCompress.Common;
using SharpCompress.Compressor;
#if BZIP2
using SharpCompress.Compressor.BZip2;
#endif
using SharpCompress.IO;
#if GZIP
using SharpCompress.Reader.GZip;
#endif
#if RAR
using SharpCompress.Reader.Rar;
#endif
#if TAR
using SharpCompress.Reader.Tar;
#endif
using SharpCompress.Reader.Zip;
#if DEFLATE
using GZipStream = SharpCompress.Compressor.Deflate.GZipStream;
#endif
namespace SharpCompress.Reader
{
internal static class ReaderFactory
{
/// <summary>
/// Opens a Reader for Non-seeking usage
/// </summary>
/// <param name="stream"></param>
/// <param name="options"></param>
/// <returns></returns>
public static IReader Open(Stream stream, Options options = Options.KeepStreamsOpen)
{
stream.CheckNotNull("stream");
RewindableStream rewindableStream = new RewindableStream(stream);
rewindableStream.StartRecording();
if (ZipArchive.IsZipFile(rewindableStream, null))
{
rewindableStream.Rewind(true);
return ZipReader.Open(rewindableStream, null, options);
}
#if GZIP
rewindableStream.Rewind(false);
if (GZipArchive.IsGZipFile(rewindableStream))
{
rewindableStream.Rewind(false);
GZipStream testStream = new GZipStream(rewindableStream, CompressionMode.Decompress);
if (TarArchive.IsTarFile(testStream))
{
rewindableStream.Rewind(true);
return new TarReader(rewindableStream, CompressionType.GZip, options);
}
rewindableStream.Rewind(true);
return GZipReader.Open(rewindableStream, options);
}
#endif
#if BZIP2
rewindableStream.Rewind(false);
if (BZip2Stream.IsBZip2(rewindableStream))
{
rewindableStream.Rewind(false);
BZip2Stream testStream = new BZip2Stream(rewindableStream, CompressionMode.Decompress, false);
#if TAR
if (TarArchive.IsTarFile(testStream))
{
rewindableStream.Rewind(true);
return new TarReader(rewindableStream, CompressionType.BZip2, options);
}
#endif
}
#endif
#if TAR
rewindableStream.Rewind(false);
if (TarArchive.IsTarFile(rewindableStream))
{
rewindableStream.Rewind(true);
return TarReader.Open(rewindableStream, options);
}
#endif
#if RAR
rewindableStream.Rewind(false);
if (RarArchive.IsRarFile(rewindableStream, options))
{
rewindableStream.Rewind(true);
return RarReader.Open(rewindableStream, options);
}
#endif
throw new InvalidOperationException("Cannot determine compressed stream type. Supported Reader Formats: Zip, GZip, BZip2, Tar, Rar");
}
}
}
@@ -0,0 +1,67 @@
using System.Collections.Generic;
using System.IO;
using SharpCompress.Common;
using SharpCompress.Common.Zip;
using SharpCompress.Common.Zip.Headers;
namespace SharpCompress.Reader.Zip
{
internal class ZipReader : AbstractReader<ZipEntry, ZipVolume>
{
private readonly StreamingZipHeaderFactory headerFactory;
private readonly ZipVolume volume;
internal ZipReader(Stream stream, Options options, string password)
: base(options, ArchiveType.Zip)
{
volume = new ZipVolume(stream, options);
headerFactory = new StreamingZipHeaderFactory(password);
}
public override ZipVolume Volume
{
get { return volume; }
}
#region Open
/// <summary>
/// Opens a ZipReader for Non-seeking usage with a single volume
/// </summary>
/// <param name="stream"></param>
/// <param name="options"></param>
/// <param name="password"></param>
/// <returns></returns>
public static ZipReader Open(Stream stream, string password = null,
Options options = Options.KeepStreamsOpen)
{
stream.CheckNotNull("stream");
return new ZipReader(stream, options, password);
}
#endregion
internal override IEnumerable<ZipEntry> GetEntries(Stream stream)
{
foreach (ZipHeader h in headerFactory.ReadStreamHeader(stream))
{
if (h != null)
{
switch (h.ZipHeaderType)
{
case ZipHeaderType.LocalEntry:
{
yield return new ZipEntry(new StreamingZipFilePart(h as LocalEntryHeader,
stream));
}
break;
case ZipHeaderType.DirectoryEnd:
{
yield break;
}
}
}
}
}
}
}
@@ -0,0 +1,491 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SharpCompress.Archive;
using SharpCompress.Common;
using SharpCompress.IO;
namespace SharpCompress
{
internal static class Utility
{
public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> items)
{
return new ReadOnlyCollection<T>(items.ToList());
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, int bits)
{
if (number >= 0)
return number >> bits;
else
return (number >> bits) + (2 << ~bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static int URShift(int number, long bits)
{
return URShift(number, (int)bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, int bits)
{
if (number >= 0)
return number >> bits;
else
return (number >> bits) + (2L << ~bits);
}
/// <summary>
/// Performs an unsigned bitwise right shift with the specified number
/// </summary>
/// <param name="number">Number to operate on</param>
/// <param name="bits">Ammount of bits to shift</param>
/// <returns>The resulting number from the shift operation</returns>
public static long URShift(long number, long bits)
{
return URShift(number, (int)bits);
}
/// <summary>
/// Fills the array with an specific value from an specific index to an specific index.
/// </summary>
/// <param name="array">The array to be filled.</param>
/// <param name="fromindex">The first index to be filled.</param>
/// <param name="toindex">The last index to be filled.</param>
/// <param name="val">The value to fill the array with.</param>
public static void Fill<T>(T[] array, int fromindex, int toindex, T val) where T : struct
{
if (array.Length == 0)
{
throw new NullReferenceException();
}
if (fromindex > toindex)
{
throw new ArgumentException();
}
if ((fromindex < 0) || ((System.Array)array).Length < toindex)
{
throw new IndexOutOfRangeException();
}
for (int index = (fromindex > 0) ? fromindex-- : fromindex; index < toindex; index++)
{
array[index] = val;
}
}
/// <summary>
/// Fills the array with an specific value.
/// </summary>
/// <param name="array">The array to be filled.</param>
/// <param name="val">The value to fill the array with.</param>
public static void Fill<T>(T[] array, T val) where T : struct
{
Fill(array, 0, array.Length, val);
}
public static void SetSize(this List<byte> list, int count)
{
if (count > list.Count)
{
for (int i = list.Count; i < count; i++)
{
list.Add(0x0);
}
}
else
{
byte[] temp = new byte[count];
list.CopyTo(temp, 0);
list.Clear();
list.AddRange(temp);
}
}
/// <summary> Read a int value from the byte array at the given position (Big Endian)
///
/// </summary>
/// <param name="array">the array to read from
/// </param>
/// <param name="pos">the offset
/// </param>
/// <returns> the value
/// </returns>
public static int readIntBigEndian(byte[] array, int pos)
{
int temp = 0;
temp |= array[pos] & 0xff;
temp <<= 8;
temp |= array[pos + 1] & 0xff;
temp <<= 8;
temp |= array[pos + 2] & 0xff;
temp <<= 8;
temp |= array[pos + 3] & 0xff;
return temp;
}
/// <summary> Read a short value from the byte array at the given position (little
/// Endian)
///
/// </summary>
/// <param name="array">the array to read from
/// </param>
/// <param name="pos">the offset
/// </param>
/// <returns> the value
/// </returns>
public static short readShortLittleEndian(byte[] array, int pos)
{
return BitConverter.ToInt16(array, pos);
}
/// <summary> Read an int value from the byte array at the given position (little
/// Endian)
///
/// </summary>
/// <param name="array">the array to read from
/// </param>
/// <param name="pos">the offset
/// </param>
/// <returns> the value
/// </returns>
public static int readIntLittleEndian(byte[] array, int pos)
{
return BitConverter.ToInt32(array, pos);
}
/// <summary> Write an int value into the byte array at the given position (Big endian)
///
/// </summary>
/// <param name="array">the array
/// </param>
/// <param name="pos">the offset
/// </param>
/// <param name="value">the value to write
/// </param>
public static void writeIntBigEndian(byte[] array, int pos, int value)
{
array[pos] = (byte)((Utility.URShift(value, 24)) & 0xff);
array[pos + 1] = (byte)((Utility.URShift(value, 16)) & 0xff);
array[pos + 2] = (byte)((Utility.URShift(value, 8)) & 0xff);
array[pos + 3] = (byte)((value) & 0xff);
}
/// <summary> Write a short value into the byte array at the given position (little
/// endian)
///
/// </summary>
/// <param name="array">the array
/// </param>
/// <param name="pos">the offset
/// </param>
/// <param name="value">the value to write
/// </param>
#if PORTABLE || NETFX_CORE
public static void WriteLittleEndian(byte[] array, int pos, short value)
{
byte[] newBytes = BitConverter.GetBytes(value);
Array.Copy(newBytes, 0, array, pos, newBytes.Length);
}
#else
public static unsafe void WriteLittleEndian(byte[] array, int pos, short value)
{
fixed (byte* numRef = &(array[pos]))
{
*((short*)numRef) = value;
}
}
#endif
/// <summary> Increment a short value at the specified position by the specified amount
/// (little endian).
/// </summary>
public static void incShortLittleEndian(byte[] array, int pos, short incrementValue)
{
short existingValue = BitConverter.ToInt16(array, pos);
existingValue += incrementValue;
WriteLittleEndian(array, pos, existingValue);
//int c = Utility.URShift(((array[pos] & 0xff) + (dv & 0xff)), 8);
//array[pos] = (byte)(array[pos] + (dv & 0xff));
//if ((c > 0) || ((dv & 0xff00) != 0))
//{
// array[pos + 1] = (byte)(array[pos + 1] + ((Utility.URShift(dv, 8)) & 0xff) + c);
//}
}
/// <summary> Write an int value into the byte array at the given position (little
/// endian)
///
/// </summary>
/// <param name="array">the array
/// </param>
/// <param name="pos">the offset
/// </param>
/// <param name="value">the value to write
/// </param>
#if PORTABLE || NETFX_CORE
public static void WriteLittleEndian(byte[] array, int pos, int value)
{
byte[] newBytes = BitConverter.GetBytes(value);
Array.Copy(newBytes, 0, array, pos, newBytes.Length);
}
#else
public static unsafe void WriteLittleEndian(byte[] array, int pos, int value)
{
fixed (byte* numRef = &(array[pos]))
{
*((int*)numRef) = value;
}
}
#endif
public static void Initialize<T>(this T[] array, Func<T> func)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = func();
}
}
public static void AddRange<T>(this ICollection<T> destination, IEnumerable<T> source)
{
foreach (T item in source)
{
destination.Add(item);
}
}
public static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
public static IEnumerable<T> AsEnumerable<T>(this T item)
{
yield return item;
}
public static void CheckNotNull(this object obj, string name)
{
if (obj == null)
{
throw new ArgumentNullException(name);
}
}
public static void CheckNotNullOrEmpty(this string obj, string name)
{
obj.CheckNotNull(name);
if (obj.Length == 0)
{
throw new ArgumentException("String is empty.");
}
}
public static void Skip(this Stream source, long advanceAmount)
{
byte[] buffer = new byte[32 * 1024];
int read = 0;
int readCount = 0;
do
{
readCount = buffer.Length;
if (readCount > advanceAmount)
{
readCount = (int)advanceAmount;
}
read = source.Read(buffer, 0, readCount);
if (read < 0)
{
break;
}
advanceAmount -= read;
if (advanceAmount == 0)
{
break;
}
} while (true);
}
public static void SkipAll(this Stream source)
{
byte[] buffer = new byte[32 * 1024];
do
{
} while (source.Read(buffer, 0, buffer.Length) == buffer.Length);
}
public static byte[] UInt32ToBigEndianBytes(uint x)
{
return new byte[]
{
(byte) ((x >> 24) & 0xff),
(byte) ((x >> 16) & 0xff),
(byte) ((x >> 8) & 0xff),
(byte) (x & 0xff)
};
}
public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime)
{
int year = iDate / 512 + 1980;
int month = iDate % 512 / 32;
int day = iDate % 512 % 32;
int hour = iTime / 2048;
int minute = iTime % 2048 / 32;
int second = iTime % 2048 % 32 * 2;
if (iDate == UInt16.MaxValue || month == 0 || day == 0)
{
year = 1980;
month = 1;
day = 1;
}
if (iTime == UInt16.MaxValue)
{
hour = minute = second = 0;
}
DateTime dt;
try
{
dt = new DateTime(year, month, day, hour, minute, second);
}
catch
{
dt = new DateTime();
}
return dt;
}
public static uint DateTimeToDosTime(this DateTime? dateTime)
{
if (dateTime == null)
{
return 0;
}
return (uint)(
(dateTime.Value.Second / 2) | (dateTime.Value.Minute << 5) | (dateTime.Value.Hour << 11) |
(dateTime.Value.Day << 16) | (dateTime.Value.Month << 21) |
((dateTime.Value.Year - 1980) << 25));
}
public static DateTime DosDateToDateTime(UInt32 iTime)
{
return DosDateToDateTime((UInt16)(iTime / 65536),
(UInt16)(iTime % 65536));
}
public static DateTime DosDateToDateTime(Int32 iTime)
{
return DosDateToDateTime((UInt32)iTime);
}
public static long TransferTo(this Stream source, Stream destination)
{
byte[] array = new byte[81920];
int count;
long total = 0;
while ((count = source.Read(array, 0, array.Length)) != 0)
{
total += count;
destination.Write(array, 0, count);
}
return total;
}
public static bool ReadFully(this Stream stream, byte[] buffer)
{
int total = 0;
int read;
while ((read = stream.Read(buffer, total, buffer.Length - total)) > 0)
{
total += read;
if (total >= buffer.Length)
{
return true;
}
}
return (total >= buffer.Length);
}
public static string TrimNulls(this string source)
{
return source.Replace('\0', ' ').Trim();
}
public static bool BinaryEquals(this byte[] source, byte[] target)
{
if (source.Length != target.Length)
{
return false;
}
for (int i = 0; i < source.Length; ++i)
{
if (source[i] != target[i])
{
return false;
}
}
return true;
}
#if PORTABLE || NETFX_CORE
public static void CopyTo(this byte[] array, byte[] destination, int index)
{
Array.Copy(array, 0, destination, index, array.Length);
}
public static long HostToNetworkOrder(long host)
{
return (int)((long)HostToNetworkOrder((int)host)
& unchecked((long)(unchecked((ulong)-1))) << 32
| ((long)HostToNetworkOrder((int)((int)host >> 32)) & unchecked((long)(unchecked((ulong)-1)))));
}
public static int HostToNetworkOrder(int host)
{
return (int)((int)(HostToNetworkOrder((short)host) & -1) << 16 | (HostToNetworkOrder((short)(host >> 16)) & -1));
}
public static short HostToNetworkOrder(short host)
{
return (short)((int)(host & 255) << 8 | ((int)host >> 8 & 255));
}
public static long NetworkToHostOrder(long network)
{
return HostToNetworkOrder(network);
}
public static int NetworkToHostOrder(int network)
{
return HostToNetworkOrder(network);
}
public static short NetworkToHostOrder(short network)
{
return HostToNetworkOrder(network);
}
#endif
}
}
@@ -0,0 +1,56 @@
using System;
using System.IO;
using SharpCompress.Common;
namespace SharpCompress.Writer
{
internal abstract class AbstractWriter : IWriter
{
private bool closeStream;
private bool isDisposed;
protected AbstractWriter(ArchiveType type)
{
this.WriterType = type;
}
protected void InitalizeStream(Stream stream, bool closeStream)
{
this.OutputStream = stream;
this.closeStream = closeStream;
}
protected Stream OutputStream { get; private set; }
public ArchiveType WriterType { get; private set; }
public abstract void Write(string filename, System.IO.Stream source, DateTime? modificationTime);
protected virtual void Dispose(bool isDisposing)
{
if (isDisposing && closeStream)
{
OutputStream.Dispose();
}
}
public void Dispose()
{
if (!isDisposed)
{
GC.SuppressFinalize(this);
Dispose(true);
isDisposed = true;
}
}
~AbstractWriter()
{
if (!isDisposed)
{
Dispose(false);
isDisposed = true;
}
}
}
}
@@ -0,0 +1,49 @@
using System;
using System.IO;
namespace SharpCompress.Writer
{
internal static class IWriterExtensions
{
public static void Write(this IWriter writer, string entryPath, Stream source)
{
writer.Write(entryPath, source, null);
}
#if !PORTABLE && !NETFX_CORE
public static void Write(this IWriter writer, string entryPath, FileInfo source)
{
if (!source.Exists)
{
throw new ArgumentException("Source does not exist: " + source.FullName);
}
using (var stream = source.OpenRead())
{
writer.Write(entryPath, stream, source.LastWriteTime);
}
}
public static void Write(this IWriter writer, string entryPath, string source)
{
writer.Write(entryPath, new FileInfo(source));
}
public static void WriteAll(this IWriter writer, string directory, string searchPattern = "*",
SearchOption option = SearchOption.TopDirectoryOnly)
{
if (!Directory.Exists(directory))
{
throw new ArgumentException("Directory does not exist: " + directory);
}
#if NET2
foreach (var file in Directory.GetFiles(directory, searchPattern, option))
#else
foreach (var file in Directory.EnumerateFiles(directory, searchPattern, option))
#endif
{
writer.Write(file.Substring(directory.Length), file);
}
}
#endif
}
}
@@ -0,0 +1,12 @@
using System;
using System.IO;
using SharpCompress.Common;
namespace SharpCompress.Writer
{
internal interface IWriter : IDisposable
{
ArchiveType WriterType { get; }
void Write(string filename, Stream source, DateTime? modificationTime);
}
}
@@ -0,0 +1,55 @@
using System;
using System.IO;
using SharpCompress.Common;
#if GZIP
using SharpCompress.Writer.GZip;
#endif
#if TAR
using SharpCompress.Writer.Tar;
#endif
using SharpCompress.Writer.Zip;
namespace SharpCompress.Writer
{
internal static class WriterFactory
{
public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionType compressionType)
{
return Open(stream, archiveType, new CompressionInfo
{
Type = compressionType
});
}
public static IWriter Open(Stream stream, ArchiveType archiveType, CompressionInfo compressionInfo)
{
switch (archiveType)
{
#if GZIP
case ArchiveType.GZip:
{
if (compressionInfo.Type != CompressionType.GZip)
{
throw new InvalidFormatException("GZip archives only support GZip compression type.");
}
return new GZipWriter(stream);
}
#endif
case ArchiveType.Zip:
{
return new ZipWriter(stream, compressionInfo, null);
}
#if TAR
case ArchiveType.Tar:
{
return new TarWriter(stream, compressionInfo);
}
#endif
default:
{
throw new NotSupportedException("Archive Type does not have a Writer: " + archiveType);
}
}
}
}
}
@@ -0,0 +1,60 @@
using System;
using System.IO;
using System.Text;
using SharpCompress.Common.Zip;
using SharpCompress.Common.Zip.Headers;
namespace SharpCompress.Writer.Zip
{
internal class ZipCentralDirectoryEntry
{
internal string FileName { get; set; }
internal DateTime? ModificationTime { get; set; }
internal string Comment { get; set; }
internal uint Crc { get; set; }
internal uint HeaderOffset { get; set; }
internal uint Compressed { get; set; }
internal uint Decompressed { get; set; }
internal uint Write(Stream outputStream, ZipCompressionMethod compression)
{
byte[] encodedFilename = Encoding.UTF8.GetBytes(FileName);
byte[] encodedComment = Encoding.UTF8.GetBytes(Comment);
outputStream.Write(new byte[] {80, 75, 1, 2, 0x3F, 0, 0x0A, 0}, 0, 8);
HeaderFlags flags = HeaderFlags.UTF8;
if (!outputStream.CanSeek)
{
flags |= HeaderFlags.UsePostDataDescriptor;
if (compression == ZipCompressionMethod.LZMA)
{
flags |= HeaderFlags.Bit1; // eos marker
}
}
outputStream.Write(BitConverter.GetBytes((ushort) flags), 0, 2);
outputStream.Write(BitConverter.GetBytes((ushort) compression), 0, 2); // zipping method
outputStream.Write(BitConverter.GetBytes(ModificationTime.DateTimeToDosTime()), 0, 4);
// zipping date and time
outputStream.Write(BitConverter.GetBytes(Crc), 0, 4); // file CRC
outputStream.Write(BitConverter.GetBytes(Compressed), 0, 4); // compressed file size
outputStream.Write(BitConverter.GetBytes(Decompressed), 0, 4); // uncompressed file size
outputStream.Write(BitConverter.GetBytes((ushort) encodedFilename.Length), 0, 2); // Filename in zip
outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // extra length
outputStream.Write(BitConverter.GetBytes((ushort) encodedComment.Length), 0, 2);
outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // disk=0
outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // file type: binary
outputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // Internal file attributes
outputStream.Write(BitConverter.GetBytes((ushort) 0x8100), 0, 2);
// External file attributes (normal/readable)
outputStream.Write(BitConverter.GetBytes(HeaderOffset), 0, 4); // Offset of header
outputStream.Write(encodedFilename, 0, encodedFilename.Length);
outputStream.Write(encodedComment, 0, encodedComment.Length);
return (uint) (8 + 2 + 2 + 4 + 4 + 4 + 4 + 2 + 2 + 2
+ 2 + 2 + 2 + 2 + 4 + encodedFilename.Length + encodedComment.Length);
}
}
}
@@ -0,0 +1,340 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SharpCompress.Common;
using SharpCompress.Common.Zip;
using SharpCompress.Common.Zip.Headers;
using SharpCompress.Compressor;
#if BZIP2
using SharpCompress.Compressor.BZip2;
#endif
using SharpCompress.Compressor.Deflate;
#if LZMA
using SharpCompress.Compressor.LZMA;
#endif
#if PPMd
using SharpCompress.Compressor.PPMd;
#endif
using SharpCompress.IO;
#if DEFLATE
using DeflateStream = SharpCompress.Compressor.Deflate.DeflateStream;
#endif
namespace SharpCompress.Writer.Zip
{
internal class ZipWriter : AbstractWriter
{
private readonly ZipCompressionMethod compression;
private readonly CompressionLevel deflateCompressionLevel;
private readonly List<ZipCentralDirectoryEntry> entries = new List<ZipCentralDirectoryEntry>();
private readonly string zipComment;
private long streamPosition;
#if PPMd
private readonly PpmdProperties ppmdProperties; // Caching properties to speed up PPMd.
#endif
public ZipWriter(Stream destination, CompressionInfo compressionInfo, string zipComment)
: base(ArchiveType.Zip)
{
this.zipComment = zipComment ?? string.Empty;
switch (compressionInfo.Type)
{
case CompressionType.None:
{
compression = ZipCompressionMethod.None;
}
break;
case CompressionType.Deflate:
{
compression = ZipCompressionMethod.Deflate;
deflateCompressionLevel = compressionInfo.DeflateCompressionLevel;
}
break;
case CompressionType.BZip2:
{
compression = ZipCompressionMethod.BZip2;
}
break;
#if LZMA
case CompressionType.LZMA:
{
compression = ZipCompressionMethod.LZMA;
}
break;
#endif
#if PPMd
case CompressionType.PPMd:
{
ppmdProperties = new PpmdProperties();
compression = ZipCompressionMethod.PPMd;
}
break;
#endif
default:
throw new InvalidFormatException("Invalid compression method: " + compressionInfo.Type);
}
InitalizeStream(destination, false);
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
uint size = 0;
foreach (ZipCentralDirectoryEntry entry in entries)
{
size += entry.Write(OutputStream, compression);
}
WriteEndRecord(size);
}
base.Dispose(isDisposing);
}
public override void Write(string entryPath, Stream source, DateTime? modificationTime)
{
Write(entryPath, source, modificationTime, null);
}
public void Write(string entryPath, Stream source, DateTime? modificationTime, string comment)
{
using (Stream output = WriteToStream(entryPath, modificationTime, comment))
{
source.TransferTo(output);
}
}
public Stream WriteToStream(string entryPath, DateTime? modificationTime, string comment)
{
entryPath = NormalizeFilename(entryPath);
modificationTime = modificationTime ?? DateTime.Now;
comment = comment ?? "";
var entry = new ZipCentralDirectoryEntry
{
Comment = comment,
FileName = entryPath,
ModificationTime = modificationTime,
HeaderOffset = (uint) streamPosition,
};
var headersize = (uint) WriteHeader(entryPath, modificationTime);
streamPosition += headersize;
return new ZipWritingStream(this, OutputStream, entry);
}
private string NormalizeFilename(string filename)
{
filename = filename.Replace('\\', '/');
int pos = filename.IndexOf(':');
if (pos >= 0)
filename = filename.Remove(0, pos + 1);
return filename.Trim('/');
}
private int WriteHeader(string filename, DateTime? modificationTime)
{
byte[] encodedFilename = Encoding.UTF8.GetBytes(filename);
OutputStream.Write(BitConverter.GetBytes(ZipHeaderFactory.ENTRY_HEADER_BYTES), 0, 4);
OutputStream.Write(new byte[] {63, 0}, 0, 2); //version
HeaderFlags flags = HeaderFlags.UTF8;
if (!OutputStream.CanSeek)
{
flags |= HeaderFlags.UsePostDataDescriptor;
if (compression == ZipCompressionMethod.LZMA)
{
flags |= HeaderFlags.Bit1; // eos marker
}
}
OutputStream.Write(BitConverter.GetBytes((ushort) flags), 0, 2);
OutputStream.Write(BitConverter.GetBytes((ushort) compression), 0, 2); // zipping method
OutputStream.Write(BitConverter.GetBytes(modificationTime.DateTimeToDosTime()), 0, 4);
// zipping date and time
OutputStream.Write(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0, 12);
// unused CRC, un/compressed size, updated later
OutputStream.Write(BitConverter.GetBytes((ushort) encodedFilename.Length), 0, 2); // filename length
OutputStream.Write(BitConverter.GetBytes((ushort) 0), 0, 2); // extra length
OutputStream.Write(encodedFilename, 0, encodedFilename.Length);
return 6 + 2 + 2 + 4 + 12 + 2 + 2 + encodedFilename.Length;
}
private void WriteFooter(uint crc, uint compressed, uint uncompressed)
{
OutputStream.Write(BitConverter.GetBytes(crc), 0, 4);
OutputStream.Write(BitConverter.GetBytes(compressed), 0, 4);
OutputStream.Write(BitConverter.GetBytes(uncompressed), 0, 4);
}
private void WriteEndRecord(uint size)
{
byte[] encodedComment = Encoding.UTF8.GetBytes(zipComment);
OutputStream.Write(new byte[] {80, 75, 5, 6, 0, 0, 0, 0}, 0, 8);
OutputStream.Write(BitConverter.GetBytes((ushort) entries.Count), 0, 2);
OutputStream.Write(BitConverter.GetBytes((ushort) entries.Count), 0, 2);
OutputStream.Write(BitConverter.GetBytes(size), 0, 4);
OutputStream.Write(BitConverter.GetBytes((uint) streamPosition), 0, 4);
OutputStream.Write(BitConverter.GetBytes((ushort) encodedComment.Length), 0, 2);
OutputStream.Write(encodedComment, 0, encodedComment.Length);
}
#region Nested type: ZipWritingStream
internal class ZipWritingStream : Stream
{
private readonly CRC32 crc = new CRC32();
private readonly ZipCentralDirectoryEntry entry;
private readonly Stream originalStream;
private readonly Stream writeStream;
private readonly ZipWriter writer;
private CountingWritableSubStream counting;
private uint decompressed;
internal ZipWritingStream(ZipWriter writer, Stream originalStream, ZipCentralDirectoryEntry entry)
{
this.writer = writer;
this.originalStream = originalStream;
writeStream = GetWriteStream(originalStream);
this.writer = writer;
this.entry = entry;
}
public override bool CanRead
{
get { return false; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return true; }
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
private Stream GetWriteStream(Stream writeStream)
{
counting = new CountingWritableSubStream(writeStream);
Stream output = counting;
switch (writer.compression)
{
case ZipCompressionMethod.None:
{
return output;
}
case ZipCompressionMethod.Deflate:
{
return new System.IO.Compression.DeflateStream(counting,
System.IO.Compression.CompressionMode.Compress, true);
}
#if BZIP2
case ZipCompressionMethod.BZip2:
{
return new BZip2Stream(counting, CompressionMode.Compress, true);
}
#endif
#if LZMA
case ZipCompressionMethod.LZMA:
{
counting.WriteByte(9);
counting.WriteByte(20);
counting.WriteByte(5);
counting.WriteByte(0);
LzmaStream lzmaStream = new LzmaStream(new LzmaEncoderProperties(!originalStream.CanSeek),
false, counting);
counting.Write(lzmaStream.Properties, 0, lzmaStream.Properties.Length);
return lzmaStream;
}
#endif
#if PPMd
case ZipCompressionMethod.PPMd:
{
counting.Write(writer.ppmdProperties.Properties, 0, 2);
return new PpmdStream(writer.ppmdProperties, counting, true);
}
#endif
default:
{
throw new NotSupportedException("CompressionMethod: " + writer.compression);
}
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
writeStream.Dispose();
entry.Crc = (uint) crc.Crc32Result;
entry.Compressed = counting.Count;
entry.Decompressed = decompressed;
if (originalStream.CanSeek)
{
originalStream.Position = entry.HeaderOffset + 6;
originalStream.WriteByte(0);
originalStream.Position = entry.HeaderOffset + 14;
writer.WriteFooter(entry.Crc, counting.Count, decompressed);
originalStream.Position = writer.streamPosition + entry.Compressed;
writer.streamPosition += entry.Compressed;
}
else
{
originalStream.Write(BitConverter.GetBytes(ZipHeaderFactory.POST_DATA_DESCRIPTOR), 0, 4);
writer.WriteFooter(entry.Crc, counting.Count, decompressed);
writer.streamPosition += entry.Compressed + 16;
}
writer.entries.Add(entry);
}
}
public override void Flush()
{
writeStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
decompressed += (uint) count;
crc.SlurpBlock(buffer, offset, count);
writeStream.Write(buffer, offset, count);
}
}
#endregion
}
}
@@ -1,3 +1,90 @@
SharpCompress/EnumExtensions.cs
SharpCompress/LazyReadOnlyCollection.cs
SharpCompress/ReadOnlyCollection.cs
SharpCompress/Utility.cs
SharpCompress/Archive/AbstractArchive.cs
SharpCompress/Archive/AbstractWritableArchive.cs
SharpCompress/Archive/AbstractWritableArchive.Extensions.cs
SharpCompress/Archive/ArchiveFactory.cs
SharpCompress/Archive/IArchive.cs
SharpCompress/Archive/IArchive.Extensions.cs
SharpCompress/Archive/IArchiveEntry.cs
SharpCompress/Archive/IArchiveEntry.Extensions.cs
SharpCompress/Archive/IArchiveExtractionListener.cs
SharpCompress/Archive/IWritableArchiveEntry.cs
SharpCompress/Archive/Zip/ZipArchive.cs
SharpCompress/Archive/Zip/ZipArchiveEntry.cs
SharpCompress/Archive/Zip/ZipWritableArchiveEntry.cs
SharpCompress/Common/ArchiveEncoding.cs
SharpCompress/Common/ArchiveException.cs
SharpCompress/Common/ArchiveExtractionEventArgs.cs
SharpCompress/Common/ArchiveType.cs
SharpCompress/Common/CompressedBytesReadEventArgs.cs
SharpCompress/Common/CompressionInfo.cs
SharpCompress/Common/CompressionType.cs
SharpCompress/Common/CryptographicException.cs
SharpCompress/Common/Entry.cs
SharpCompress/Common/EntryStream.cs
SharpCompress/Common/ExtractionException.cs
SharpCompress/Common/ExtractOptions.cs
SharpCompress/Common/FilePart.cs
SharpCompress/Common/FilePartExtractionBeginEventArgs.cs
SharpCompress/Common/FlagUtility.cs
SharpCompress/Common/IEntry.cs
SharpCompress/Common/IExtractionListener.cs
SharpCompress/Common/IncompleteArchiveException.cs
SharpCompress/Common/InvalidFormatException.cs
SharpCompress/Common/IVolume.cs
SharpCompress/Common/MultipartStreamRequiredException.cs
SharpCompress/Common/MultiVolumeExtractionException.cs
SharpCompress/Common/Options.cs
SharpCompress/Common/PasswordProtectedException.cs
SharpCompress/Common/Volume.cs
SharpCompress/Common/Zip/PkwareTraditionalCryptoStream.cs
SharpCompress/Common/Zip/PkwareTraditionalEncryptionData.cs
SharpCompress/Common/Zip/SeekableZipFilePart.cs
SharpCompress/Common/Zip/SeekableZipHeaderFactory.cs
SharpCompress/Common/Zip/StreamingZipFilePart.cs
SharpCompress/Common/Zip/StreamingZipHeaderFactory.cs
SharpCompress/Common/Zip/WinzipAesCryptoStream.cs
SharpCompress/Common/Zip/WinzipAesEncryptionData.cs
SharpCompress/Common/Zip/WinzipAesKeySize.cs
SharpCompress/Common/Zip/ZipCompressionMethod.cs
SharpCompress/Common/Zip/ZipEntry.cs
SharpCompress/Common/Zip/ZipFilePart.cs
SharpCompress/Common/Zip/ZipHeaderFactory.cs
SharpCompress/Common/Zip/ZipVolume.cs
SharpCompress/Common/Zip/Headers/DirectoryEndHeader.cs
SharpCompress/Common/Zip/Headers/DirectoryEntryHeader.cs
SharpCompress/Common/Zip/Headers/HeaderFlags.cs
SharpCompress/Common/Zip/Headers/IgnoreHeader.cs
SharpCompress/Common/Zip/Headers/LocalEntryHeader.cs
SharpCompress/Common/Zip/Headers/SplitHeader.cs
SharpCompress/Common/Zip/Headers/ZipFileEntry..cs
SharpCompress/Common/Zip/Headers/ZipHeader.cs
SharpCompress/Common/Zip/Headers/ZipHeaderType.cs
SharpCompress/Compressor/CompressionMode.cs
SharpCompress/Compressor/Deflate/CRC32.cs
SharpCompress/Compressor/Deflate/ZlibBase.cs
SharpCompress/IO/AppendingStream.cs
SharpCompress/IO/CountingWritableSubStream.cs
SharpCompress/IO/ListeningStream.cs
SharpCompress/IO/MarkingBinaryReader.cs
SharpCompress/IO/NonDisposingStream.cs
SharpCompress/IO/ReadOnlySubStream.cs
SharpCompress/IO/RewindableStream.cs
SharpCompress/IO/StreamingMode.cs
SharpCompress/Reader/AbstractReader.cs
SharpCompress/Reader/IReader.cs
SharpCompress/Reader/IReader.Extensions.cs
SharpCompress/Reader/ReaderFactory.cs
SharpCompress/Reader/Zip/ZipReader.cs
SharpCompress/Writer/AbstractWriter.cs
SharpCompress/Writer/IWriter.cs
SharpCompress/Writer/IWriter.Extensions.cs
SharpCompress/Writer/WriterFactory.cs
SharpCompress/Writer/Zip/ZipCentralDirectoryEntry.cs
SharpCompress/Writer/Zip/ZipWriter.cs
AssemblyInfo.cs
TypeForwarders.cs
ZipArchive.cs
@@ -0,0 +1 @@
System.IO.Compression/ZipTest.cs
@@ -0,0 +1,226 @@
//
// ZipTests.cs
//
// Author:
// Joao Matos <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using NUnit.Framework;
namespace MonoTests.System.IO.Compression
{
[TestFixture]
public class ZipArchiveTests
{
static string GetSHA1HashFromFile(Stream stream)
{
using (var sha1 = SHA1.Create())
{
return BitConverter.ToString(sha1.ComputeHash(stream))
.Replace("-", string.Empty);
}
}
[Test]
public void ZipGetEntryReadMode()
{
File.Copy("archive.zip", "test.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNotNull(entry);
var nullEntry = archive.GetEntry("nonexisting");
Assert.IsNull(nullEntry);
}
}
[Test]
public void ZipGetEntryCreateMode()
{
File.Copy("archive.zip", "test.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open),
ZipArchiveMode.Create))
{
try {
archive.GetEntry("foo");
} catch(NotSupportedException ex) {
return;
}
Assert.Fail();
}
}
[Test]
public void ZipGetEntryUpdateMode()
{
File.Copy("archive.zip", "test.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNotNull(entry);
var nullEntry = archive.GetEntry("nonexisting");
Assert.IsNull(nullEntry);
}
}
[Test]
public void ZipGetEntryOpen()
{
File.Copy("archive.zip", "test.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNotNull(entry);
var foo = entry.Open();
Assert.AreEqual("F1D2D2F924E986AC86FDF7B36C94BCDF32BEEC15",
GetSHA1HashFromFile(foo));
}
}
[Test]
public void ZipGetEntryDeleteReadMode()
{
File.Copy("archive.zip", "delete.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("delete.zip", FileMode.Open),
ZipArchiveMode.Update))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNotNull(entry);
entry.Delete();
}
using (var archive = new ZipArchive(File.Open("delete.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNull(entry);
}
}
[Test]
public void ZipGetEntryDeleteUpdateMode()
{
File.Copy("archive.zip", "delete.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("delete.zip", FileMode.Open),
ZipArchiveMode.Update))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNotNull(entry);
entry.Delete();
}
using (var archive = new ZipArchive(File.Open("delete.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNull(entry);
}
}
[Test]
public void ZipCreateArchive()
{
using (var archive = new ZipArchive(File.Open("create.zip", FileMode.Create),
ZipArchiveMode.Create))
{
var entry = archive.CreateEntry("foo.txt");
using (var stream = entry.Open())
{
}
}
using (var archive = new ZipArchive(File.Open("create.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entry = archive.GetEntry("foo.txt");
Assert.IsNotNull(entry);
}
}
[Test]
public void ZipEnumerateEntriesReadMode()
{
File.Copy("archive.zip", "test.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entries = archive.Entries;
Assert.AreEqual(5, entries.Count);
Assert.AreEqual("bar.txt", entries[0].FullName);
Assert.AreEqual("foo.txt", entries[1].FullName);
Assert.AreEqual("foobar/", entries[2].FullName);
Assert.AreEqual("foobar/bar.txt", entries[3].FullName);
Assert.AreEqual("foobar/foo.txt", entries[4].FullName);
}
}
[Test]
public void ZipEnumerateEntriesUpdateMode()
{
File.Copy("archive.zip", "test.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open),
ZipArchiveMode.Read))
{
var entries = archive.Entries;
Assert.AreEqual(5, entries.Count);
Assert.AreEqual("bar.txt", entries[0].FullName);
Assert.AreEqual("foo.txt", entries[1].FullName);
Assert.AreEqual("foobar/", entries[2].FullName);
Assert.AreEqual("foobar/bar.txt", entries[3].FullName);
Assert.AreEqual("foobar/foo.txt", entries[4].FullName);
}
}
[Test]
public void ZipEnumerateEntriesCreateMode()
{
File.Copy("archive.zip", "test.zip", overwrite: true);
using (var archive = new ZipArchive(File.Open("test.zip", FileMode.Open),
ZipArchiveMode.Create))
{
try {
archive.Entries.ToList();
} catch(NotSupportedException ex) {
return;
}
Assert.Fail();
}
}
}
}
+163 -20
View File
@@ -1,7 +1,8 @@
//
// ZipArchive.cs
// ZipArchiveEntry.cs
//
// Author:
// Joao Matos <[email protected]>
// Martin Baulig <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc. (http://www.xamarin.com)
@@ -23,74 +24,216 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using SharpCompress.Common;
namespace System.IO.Compression
{
[MonoTODO]
public class ZipArchive : IDisposable
{
internal Stream stream;
internal readonly bool leaveStreamOpen;
internal readonly ZipArchiveMode mode;
internal Encoding entryNameEncoding;
internal bool disposed;
internal Dictionary<string, ZipArchiveEntry> entries;
internal SharpCompress.Archive.Zip.ZipArchive zipFile;
public ZipArchive (Stream stream)
{
throw new NotImplementedException ();
if (stream == null)
throw new ArgumentNullException("stream");
this.stream = stream;
mode = ZipArchiveMode.Read;
CreateZip(stream, mode);
}
public ZipArchive (Stream stream, ZipArchiveMode mode)
: this (stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
this.stream = stream;
this.mode = mode;
CreateZip(stream, mode);
}
public ZipArchive (Stream stream, ZipArchiveMode mode,
bool leaveOpen)
: this (stream, mode)
public ZipArchive (Stream stream, ZipArchiveMode mode, bool leaveOpen)
{
if (stream == null)
throw new ArgumentNullException("stream");
this.stream = stream;
this.mode = mode;
leaveStreamOpen = leaveOpen;
CreateZip(stream, mode);
}
public ZipArchive (Stream stream, ZipArchiveMode mode,
bool leaveOpen, Encoding entryNameEncoding)
: this (stream, mode, leaveOpen)
public ZipArchive (Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding entryNameEncoding)
{
if (stream == null)
throw new ArgumentNullException("stream");
this.stream = stream;
this.mode = mode;
leaveStreamOpen = leaveOpen;
this.entryNameEncoding = entryNameEncoding;
CreateZip(stream, mode);
}
private void CreateZip(Stream stream, ZipArchiveMode mode)
{
if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update)
throw new ArgumentOutOfRangeException("mode");
// If the mode parameter is set to Read, the stream must support reading.
if (mode == ZipArchiveMode.Read && !stream.CanRead)
throw new ArgumentException("Stream must support reading for Read archive mode");
// If the mode parameter is set to Create, the stream must support writing.
if (mode == ZipArchiveMode.Create && !stream.CanWrite)
throw new ArgumentException("Stream must support writing for Create archive mode");
// If the mode parameter is set to Update, the stream must support reading, writing, and seeking.
if (mode == ZipArchiveMode.Update && (!stream.CanRead || !stream.CanWrite || !stream.CanSeek))
throw new ArgumentException("Stream must support reading, writing and seeking for Update archive mode");
try {
zipFile = mode == ZipArchiveMode.Create ?
SharpCompress.Archive.Zip.ZipArchive.Create() :
SharpCompress.Archive.Zip.ZipArchive.Open(stream);
} catch (Exception) {
throw new InvalidDataException("The contents of the stream are not in the zip archive format.");
}
entries = new Dictionary<string, ZipArchiveEntry>();
if (Mode != ZipArchiveMode.Create) {
foreach (var entry in zipFile.Entries) {
var zipEntry = new ZipArchiveEntry(this, entry);
entries[entry.Key] = zipEntry;
}
}
}
public ReadOnlyCollection<ZipArchiveEntry> Entries {
get {
throw new NotImplementedException ();
if (disposed)
throw new ObjectDisposedException("The zip archive has been disposed.");
if (Mode == ZipArchiveMode.Create)
throw new NotSupportedException("Cannot access entries in Create mode.");
if (zipFile == null)
throw new InvalidDataException("The zip archive is corrupt, and its entries cannot be retrieved.");
if (entries == null)
return new ReadOnlyCollection<ZipArchiveEntry>(new List<ZipArchiveEntry>());
return new ReadOnlyCollection<ZipArchiveEntry>(entries.Values.ToList());
}
}
public ZipArchiveMode Mode {
get {
throw new NotImplementedException ();
if (disposed)
throw new ObjectDisposedException("The zip archive has been disposed.");
return mode;
}
}
public ZipArchiveEntry CreateEntry (string entryName)
{
throw new NotImplementedException ();
if (disposed)
throw new ObjectDisposedException("The zip archive has been disposed.");
return CreateEntry(entryName, CompressionLevel.Optimal);
}
public ZipArchiveEntry CreateEntry (string entryName,
CompressionLevel compressionLevel)
public ZipArchiveEntry CreateEntry (string entryName, CompressionLevel compressionLevel)
{
throw new NotImplementedException ();
if (disposed)
throw new ObjectDisposedException("The zip archive has been disposed.");
if (entryName == string.Empty)
throw new ArgumentException("Entry name cannot be empty.");
if (entryName == null)
throw new ArgumentNullException("entryName");
if (mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update)
throw new NotSupportedException("The zip archive does not support writing.");
if (zipFile == null)
throw new InvalidDataException("The zip archive is corrupt, and its entries cannot be retrieved.");
var memoryStream = new MemoryStream();
var entry = zipFile.AddEntry(entryName, memoryStream);
var archiveEntry = new ZipArchiveEntry(this, entry);
entries[entryName] = archiveEntry;
return archiveEntry;
}
public ZipArchiveEntry GetEntry (string entryName)
{
throw new NotImplementedException ();
if (disposed)
throw new ObjectDisposedException("The zip archive has been disposed.");
if (entryName == string.Empty)
throw new ArgumentException("Entry name cannot be empty.");
if (entryName == null)
throw new ArgumentNullException("entryName");
if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Update)
throw new NotSupportedException("The zip archive does not support reading.");
if (zipFile == null)
throw new InvalidDataException("The zip archive is corrupt, and its entries cannot be retrieved.");
return entries.ContainsKey(entryName) ? entries[entryName] : null;
}
private void Save()
{
using (var newZip = new MemoryStream()) {
zipFile.SaveTo(newZip, CompressionType.Deflate);
stream.SetLength(0);
stream.Position = 0;
newZip.Position = 0;
newZip.CopyTo(stream);
}
}
protected virtual void Dispose (bool disposing)
{
throw new NotImplementedException ();
if (disposed)
return;
if (mode != ZipArchiveMode.Read)
Save();
disposed = true;
if (leaveStreamOpen)
return;
if (stream != null) {
stream.Dispose();
stream = null;
}
}
public void Dispose ()
{
throw new NotImplementedException ();
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
@@ -2,6 +2,7 @@
// ZipArchiveEntry.cs
//
// Author:
// Joao Matos <[email protected]>
// Martin Baulig <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc. (http://www.xamarin.com)
@@ -23,50 +24,103 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using SharpCompress.Archive;
namespace System.IO.Compression
{
[MonoTODO]
public class ZipArchiveEntry
{
readonly SharpCompress.Archive.Zip.ZipArchiveEntry entry;
private Stream openStream;
private bool wasDeleted;
internal ZipArchiveEntry(ZipArchive archive, SharpCompress.Archive.Zip.ZipArchiveEntry entry)
{
if (archive == null)
throw new ArgumentNullException("archive");
if (entry == null)
throw new ArgumentNullException("entry");
Archive = archive;
this.entry = entry;
}
public ZipArchive Archive {
get;
private set;
}
public long CompressedLength {
get;
private set;
get {
if (Archive.Mode == ZipArchiveMode.Create)
throw new InvalidOperationException("Property cannot be retrieved when the mode is set to Create");
return entry.CompressedSize;
}
}
public string FullName {
get;
private set;
get { return entry.Key; }
}
public DateTimeOffset LastWriteTime {
get; set;
get { return entry.LastModifiedTime.GetValueOrDefault(); }
set { entry.LastModifiedTime = value.DateTime; }
}
public long Length {
get;
private set;
get {
if (Archive.Mode == ZipArchiveMode.Create)
throw new InvalidOperationException("Property cannot be retrieved when the mode is set to Create");
return entry.Size;
}
}
public string Name {
get;
private set;
get { return Path.GetFileName(entry.Key); }
}
public void Delete ()
public void Delete()
{
throw new NotImplementedException ();
if (Archive.disposed)
throw new ObjectDisposedException("The zip archive for this entry has been disposed.");
if (Archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException("The zip archive for this entry was opened in a mode other than Update.");
if (openStream != null)
throw new IOException("The entry is already open for reading or writing.");
wasDeleted = true;
Archive.zipFile.RemoveEntry(entry);
}
public Stream Open ()
public Stream Open()
{
throw new NotImplementedException ();
if (Archive.disposed)
throw new ObjectDisposedException("The zip archive for this entry has been disposed.");
if (openStream != null && Archive.Mode == ZipArchiveMode.Update)
throw new IOException("The entry is already currently open for writing.");
if (wasDeleted)
throw new IOException("The entry has been deleted from the archive.");
if (Archive.Mode == ZipArchiveMode.Create && openStream != null)
throw new IOException("The archive for this entry was opened with the Create mode, and this entry has already been written to.");
var memoryStream = new MemoryStream();
openStream = memoryStream;
if (Archive.Mode == ZipArchiveMode.Read || Archive.Mode == ZipArchiveMode.Update)
entry.WriteTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream;
}
}
}
@@ -23,8 +23,6 @@
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace System.IO.Compression
{
public enum ZipArchiveMode
Binary file not shown.