From f36ca373206340a25b1d3bb226acc7b679128a7c Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Mon, 13 Apr 2020 14:19:12 +0100 Subject: [PATCH 001/162] Merge PR #432: Throw ArgumentNullException in BZip2 Change the BZip2 Compress/Decompress functions to throw ArgumentNullxception rather than Exception when null stream parameters are provided --- src/ICSharpCode.SharpZipLib/BZip2/BZip2.cs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/BZip2/BZip2.cs b/src/ICSharpCode.SharpZipLib/BZip2/BZip2.cs index ec6ff9402..4bd48b035 100644 --- a/src/ICSharpCode.SharpZipLib/BZip2/BZip2.cs +++ b/src/ICSharpCode.SharpZipLib/BZip2/BZip2.cs @@ -17,10 +17,11 @@ public static class BZip2 /// Both streams are closed on completion if true. public static void Decompress(Stream inStream, Stream outStream, bool isStreamOwner) { - if (inStream == null || outStream == null) - { - throw new Exception("Null Stream"); - } + if (inStream == null) + throw new ArgumentNullException(nameof(inStream)); + + if (outStream == null) + throw new ArgumentNullException(nameof(outStream)); try { @@ -51,10 +52,11 @@ public static void Decompress(Stream inStream, Stream outStream, bool isStreamOw /// the lowest compression and 9 the highest. public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int level) { - if (inStream == null || outStream == null) - { - throw new Exception("Null Stream"); - } + if (inStream == null) + throw new ArgumentNullException(nameof(inStream)); + + if (outStream == null) + throw new ArgumentNullException(nameof(outStream)); try { From 195b4e2275f9d4d486b44add324d574c851db2a3 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 31 May 2020 21:13:41 +0100 Subject: [PATCH 002/162] Merge PR#469: Add test for writing using a zero byte buffer --- .../Zip/StreamHandling.cs | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index 21c3eacbd..bcabf1c86 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -2,6 +2,7 @@ using ICSharpCode.SharpZipLib.Tests.TestSupport; using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; +using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tests.Zip @@ -191,6 +192,49 @@ public void EmptyZipEntries() Assert.AreEqual(extractCount, 0, "No data should be read from empty entries"); } + /// + /// Test that calling Write with 0 bytes behaves. + /// See issue @ https://github.com/icsharpcode/SharpZipLib/issues/123. + /// + [Test] + [Category("Zip")] + public void TestZeroByteWrite() + { + using (var ms = new MemoryStreamWithoutSeek()) + { + using (var outStream = new ZipOutputStream(ms) { IsStreamOwner = false }) + { + var ze = new ZipEntry("Striped Marlin"); + outStream.PutNextEntry(ze); + + var buffer = Array.Empty(); + outStream.Write(buffer, 0, 0); + } + + ms.Seek(0, SeekOrigin.Begin); + + using (var inStream = new ZipInputStream(ms) { IsStreamOwner = false }) + { + int extractCount = 0; + byte[] decompressedData = new byte[100]; + + while (inStream.GetNextEntry() != null) + { + while (true) + { + int numRead = inStream.Read(decompressedData, extractCount, decompressedData.Length); + if (numRead <= 0) + { + break; + } + extractCount += numRead; + } + } + Assert.Zero(extractCount, "No data should be read from empty entries"); + } + } + } + [Test] [Category("Zip")] public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLength) From 97a317a44dd874521affdd75d67aeddfef777b03 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 21:05:19 +0100 Subject: [PATCH 003/162] Merge PR #473: Add a Nuget badge to readme.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b6a9559d1..9a06f1ca8 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# SharpZipLib [![Build status](https://ci.appveyor.com/api/projects/status/wuf8l79mypqsbor3/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/sharpziplib/branch/master) [![Join the chat at https://gitter.im/icsharpcode/SharpZipLib](https://badges.gitter.im/icsharpcode/SharpZipLib.svg)](https://gitter.im/icsharpcode/SharpZipLib?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +# SharpZipLib [![Build status](https://ci.appveyor.com/api/projects/status/wuf8l79mypqsbor3/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/sharpziplib/branch/master) [![Join the chat at https://gitter.im/icsharpcode/SharpZipLib](https://badges.gitter.im/icsharpcode/SharpZipLib.svg)](https://gitter.im/icsharpcode/SharpZipLib?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) The SharpZipLib project is looking for a new maintainer - please read [State of the Union August 2017](https://github.com/icsharpcode/SharpZipLib/issues/187) From 861a313873c432c2ad63aea702863e8f818a4940 Mon Sep 17 00:00:00 2001 From: Bastian Eicher Date: Fri, 19 Jun 2020 22:09:23 +0200 Subject: [PATCH 004/162] Merge PR #463: Improve support for Unix timestamps in ZIP archives * Store ZipEntry.DateTime in dedicated backing field This allows reading values with a higher resolution than DOS time (2 second accuracy). * Fix getting unix modification time in ZIP files InfoZIP actually does respect a file's modification time, even if the access time and/or creation time are not set. * Remove backing field for ZipEntry.DosTime, convert to and from ZipEntry.DateTime instead This prevents the two values from becoming potentially inconsistent. --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 110 ++++++++---------- .../Zip/ZipEntryHandling.cs | 2 + 2 files changed, 51 insertions(+), 61 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index d5105b5ab..a6241cb0f 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -238,7 +238,7 @@ public ZipEntry(ZipEntry entry) size = entry.size; compressedSize = entry.compressedSize; crc = entry.crc; - dosTime = entry.dosTime; + dateTime = entry.DateTime; method = entry.method; comment = entry.comment; versionToExtract = entry.versionToExtract; @@ -696,7 +696,38 @@ public long DosTime } else { - return dosTime; + var year = (uint)DateTime.Year; + var month = (uint)DateTime.Month; + var day = (uint)DateTime.Day; + var hour = (uint)DateTime.Hour; + var minute = (uint)DateTime.Minute; + var second = (uint)DateTime.Second; + + if (year < 1980) + { + year = 1980; + month = 1; + day = 1; + hour = 0; + minute = 0; + second = 0; + } + else if (year > 2107) + { + year = 2107; + month = 12; + day = 31; + hour = 23; + minute = 59; + second = 59; + } + + return ((year - 1980) & 0x7f) << 25 | + (month << 21) | + (day << 16) | + (hour << 11) | + (minute << 5) | + (second >> 1); } } @@ -704,10 +735,15 @@ public long DosTime { unchecked { - dosTime = (uint)value; + var dosTime = (uint)value; + uint sec = Math.Min(59, 2 * (dosTime & 0x1f)); + uint min = Math.Min(59, (dosTime >> 5) & 0x3f); + uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f); + uint mon = Math.Max(1, Math.Min(12, ((uint)(value >> 21) & 0xf))); + uint year = ((dosTime >> 25) & 0x7f) + 1980; + int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((value >> 16) & 0x1f))); + DateTime = new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Utc); } - - known |= Known.Time; } } @@ -721,49 +757,13 @@ public DateTime DateTime { get { - uint sec = Math.Min(59, 2 * (dosTime & 0x1f)); - uint min = Math.Min(59, (dosTime >> 5) & 0x3f); - uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f); - uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf))); - uint year = ((dosTime >> 25) & 0x7f) + 1980; - int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f))); - return new System.DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec); + return dateTime; } set { - var year = (uint)value.Year; - var month = (uint)value.Month; - var day = (uint)value.Day; - var hour = (uint)value.Hour; - var minute = (uint)value.Minute; - var second = (uint)value.Second; - - if (year < 1980) - { - year = 1980; - month = 1; - day = 1; - hour = 0; - minute = 0; - second = 0; - } - else if (year > 2107) - { - year = 2107; - month = 12; - day = 31; - hour = 23; - minute = 59; - second = 59; - } - - DosTime = ((year - 1980) & 0x7f) << 25 | - (month << 21) | - (day << 16) | - (hour << 11) | - (minute << 5) | - (second >> 1); + dateTime = value; + known |= Known.Time; } } @@ -1088,14 +1088,14 @@ internal void ProcessExtraData(bool localHeader) } } - DateTime = GetDateTime(extraData); + DateTime = GetDateTime(extraData) ?? DateTime; if (method == CompressionMethod.WinZipAES) { ProcessAESExtraData(extraData); } } - private DateTime GetDateTime(ZipExtraData extraData) + private DateTime? GetDateTime(ZipExtraData extraData) { // Check for NT timestamp // NOTE: Disable by default to match behavior of InfoZIP @@ -1107,22 +1107,10 @@ private DateTime GetDateTime(ZipExtraData extraData) // Check for Unix timestamp ExtendedUnixData unixData = extraData.GetData(); - if (unixData != null && - // Only apply modification time, but require all other values to be present - // This is done to match InfoZIP's behaviour - ((unixData.Include & ExtendedUnixData.Flags.ModificationTime) != 0) && - ((unixData.Include & ExtendedUnixData.Flags.AccessTime) != 0) && - ((unixData.Include & ExtendedUnixData.Flags.CreateTime) != 0)) + if (unixData != null && unixData.Include.HasFlag(ExtendedUnixData.Flags.ModificationTime)) return unixData.ModificationTime; - // Fall back to DOS time - uint sec = Math.Min(59, 2 * (dosTime & 0x1f)); - uint min = Math.Min(59, (dosTime >> 5) & 0x3f); - uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f); - uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf))); - uint year = ((dosTime >> 25) & 0x7f) + 1980; - int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f))); - return new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Utc); + return null; } // For AES the method in the entry is 99, and the real compression method is in the extradata @@ -1328,7 +1316,7 @@ public static string CleanName(string name) private ulong compressedSize; private ushort versionToExtract; // Version required to extract (library handles <= 2.0) private uint crc; - private uint dosTime; + private DateTime dateTime; private CompressionMethod method = CompressionMethod.Deflated; private byte[] extra; diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryHandling.cs index 2babfafd2..4b08f7519 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryHandling.cs @@ -195,10 +195,12 @@ public void DateAndTime() // Over the limit are set to max. ze.DateTime = new DateTime(2108, 1, 1); + ze.DosTime = ze.DosTime; Assert.AreEqual(new DateTime(2107, 12, 31, 23, 59, 58), ze.DateTime); // Under the limit are set to min. ze.DateTime = new DateTime(1906, 12, 4); + ze.DosTime = ze.DosTime; Assert.AreEqual(new DateTime(1980, 1, 1, 0, 0, 0), ze.DateTime); } From 37c3a9e22e074029c7190ac440dc8c95449ce464 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 21:10:35 +0100 Subject: [PATCH 005/162] Merge PR #468: Add test for adding empty folders to archives using FastZip --- .../Zip/FastZipHandling.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index ebb44df36..b1a0eb100 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -93,6 +93,45 @@ public void ExtractEmptyDirectories() Assert.IsTrue(Directory.Exists(targetDir), "Empty directory should be created"); } + /// + /// Test that FastZip can create empty directory entries in archives. + /// + [TestCase(null)] + [TestCase("password")] + [Category("Zip")] + [Category("CreatesTempFile")] + public void CreateEmptyDirectories(string password) + { + using (var tempFilePath = new Utils.TempDir()) + { + string name = Path.Combine(tempFilePath.Fullpath, "x.zip"); + + // Create empty test folders (The folder that we'll zip, and the test sub folder). + string archiveRootDir = Path.Combine(tempFilePath.Fullpath, ZipTempDir); + string targetDir = Path.Combine(archiveRootDir, "floyd"); + Directory.CreateDirectory(targetDir); + + // Create the archive with FastZip + var fastZip = new FastZip + { + CreateEmptyDirectories = true, + Password = password, + }; + fastZip.CreateZip(name, archiveRootDir, true, null); + + // Test that the archive contains the empty folder entry + using (var zipFile = new ZipFile(name)) + { + Assert.That(zipFile.Count, Is.EqualTo(1), "Should only be one entry in the file"); + + var folderEntry = zipFile.GetEntry("floyd/"); + Assert.That(folderEntry.IsDirectory, Is.True, "The entry must be a folder"); + + Assert.IsTrue(zipFile.TestArchive(true)); + } + } + } + [Test] [Category("Zip")] [Category("CreatesTempFile")] From 4d8c4a9f54670feda62ada9f29a0282e4c6a1a53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Fri, 19 Jun 2020 17:12:46 -0300 Subject: [PATCH 006/162] Merge PR #467: Allow seeking a PartialInputStream to the very end --- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 9a7f64e9f..6cacf2da8 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -4229,7 +4229,7 @@ public override long Seek(long offset, SeekOrigin origin) throw new ArgumentException("Negative position is invalid"); } - if (newPos >= end_) + if (newPos > end_) { throw new IOException("Cannot seek past end"); } @@ -4266,7 +4266,7 @@ public override long Position throw new ArgumentException("Negative position is invalid"); } - if (newPos >= end_) + if (newPos > end_) { throw new InvalidOperationException("Cannot seek past end"); } From 00ee6531faa726c1a043214c76a223608ff691de Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 21:14:44 +0100 Subject: [PATCH 007/162] Merge PR #466: Improve the ZipFileStoreAesPartialRead test to test multiple block sizes --- .../Zip/ZipEncryptionHandling.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index fdacb69e2..954e63875 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -150,7 +150,7 @@ public void ZipFileStoreAes() [Test] [Category("Encryption")] [Category("Zip")] - public void ZipFileStoreAesPartialRead() + public void ZipFileStoreAesPartialRead([Values(1, 7, 17)] int readSize) { string password = "password"; @@ -179,16 +179,16 @@ public void ZipFileStoreAesPartialRead() { using (var zis = zipFile.GetInputStream(entry)) { - byte[] buffer = new byte[1]; + byte[] buffer = new byte[readSize]; while (true) { - int b = zis.ReadByte(); + int read = zis.Read(buffer, 0, readSize); - if (b == -1) + if (read == 0) break; - ms.WriteByte((byte)b); + ms.Write(buffer, 0, read); } } From 5addf0f9bb595d2161024f060db15ccf0c68d3ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Fri, 19 Jun 2020 17:16:48 -0300 Subject: [PATCH 008/162] Merge PR #465: Fixed bug in ZipAESStream.ReadBufferedData copyCount was being computed but not passed to Array.Copy(), which caused an exception to be thrown when enough bytes were read from an encrypted stream. --- src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs index ffafee5df..4f649e8a9 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs @@ -163,7 +163,7 @@ private int ReadBufferedData(byte[] buffer, int offset, int count) { int copyCount = Math.Min(count, _transformBufferFreePos - _transformBufferStartPos); - Array.Copy(_transformBuffer, _transformBufferStartPos, buffer, offset, count); + Array.Copy(_transformBuffer, _transformBufferStartPos, buffer, offset, copyCount); _transformBufferStartPos += copyCount; return copyCount; From c7a91b86a8bf120a25a1c8948881cf650777516a Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 21:17:36 +0100 Subject: [PATCH 009/162] Merge PR #453: Fix the 7-zip interop tests in the .Net 4.6 test build --- .../ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index 954e63875..6b14cad2c 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -384,7 +384,8 @@ public static bool TryGet7zBinPath(out string path7z) { var p = Process.Start(new ProcessStartInfo(testPath, "i") { - RedirectStandardOutput = true + RedirectStandardOutput = true, + UseShellExecute = false }); while (!p.StandardOutput.EndOfStream && (DateTime.Now - p.StartTime) < runTimeLimit) { From 3c32813b2aa03472bae4065648966a518d8e9a8d Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 21:19:02 +0100 Subject: [PATCH 010/162] Merge PR #461: Fix Exception doc comments * fix doc comment in ZipInputStream.BodyRead * fix doc comment in ZipOutputStream.SetComment --- src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs index c6ac79faf..b9c8d8c35 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs @@ -584,7 +584,7 @@ public override int Read(byte[] buffer, int offset, int count) /// /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. /// - /// + /// /// An i/o error occured. /// /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index b9f1965dd..8f0784513 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -95,7 +95,7 @@ public bool IsFinished /// /// The comment text for the entire archive. /// - /// + /// /// The converted comment is longer than 0xffff bytes. /// public void SetComment(string comment) From 4a5ae32e89fc7ac6daa9f1fa551d8f0465f9affc Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 21:20:18 +0100 Subject: [PATCH 011/162] Merge PR #448: Fix unit test assert argument order --- test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs | 2 +- test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs | 4 ++-- test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs b/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs index 056a2625b..34dc288b1 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs @@ -80,7 +80,7 @@ public void CreateEmptyArchive() pos += numRead; } - Assert.AreEqual(pos, 0); + Assert.Zero(pos); } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs index c7945f142..69e0936bc 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs @@ -35,7 +35,7 @@ public void EmptyTar() } Assert.IsTrue(ms.GetBuffer().Length > 0, "Archive size must be > zero"); - Assert.AreEqual(ms.GetBuffer().Length % recordSize, 0, "Archive size must be a multiple of record size"); + Assert.Zero(ms.GetBuffer().Length % recordSize, "Archive size must be a multiple of record size"); var ms2 = new MemoryStream(); ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); @@ -769,7 +769,7 @@ public void SingleLargeEntry() var tis = new TarInputStream(bs); var entry = tis.GetNextEntry(); - Assert.AreEqual(entry.Name, EntryName); + Assert.AreEqual(EntryName, entry.Name); return tis; }, output: bs => diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index bcabf1c86..5ba337f51 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -189,7 +189,7 @@ public void EmptyZipEntries() } } inStream.Close(); - Assert.AreEqual(extractCount, 0, "No data should be read from empty entries"); + Assert.Zero(extractCount, "No data should be read from empty entries"); } /// @@ -404,7 +404,7 @@ public void SingleLargeEntry() var zis = new ZipInputStream(bs); var entry = zis.GetNextEntry(); - Assert.AreEqual(entry.Name, EntryName); + Assert.AreEqual(EntryName, entry.Name); Assert.IsTrue((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0); return zis; }, From 4bbcb4b0860101c9f600bd911dc08dc959b2f5f6 Mon Sep 17 00:00:00 2001 From: Yusuke Ito Date: Sat, 20 Jun 2020 05:34:43 +0900 Subject: [PATCH 012/162] Merge PR #364: Add nameEncoding parameter to Tar entries * add encoding parameter to creating tar entry default is same as current master behavior(omit upper byte) * add encoding tests(cp932) and add doc comment(#364) * add header bytes test and mark obsolete methods without encodings(#364) but IEntryFactory does not considering name encoding. * forget to mark as obsoleting(#364) * add doc comment for name encoding parameter (#364) --- src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 60 ++++- src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs | 58 ++++- src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs | 227 +++++++++++++++--- .../Tar/TarInputStream.cs | 55 ++++- .../Tar/TarOutputStream.cs | 54 ++++- .../Tar/TarTests.cs | 107 +++++++-- 6 files changed, 480 insertions(+), 81 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs index 133b33081..659334b7f 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs @@ -100,7 +100,22 @@ protected TarArchive(TarOutputStream stream) /// /// The stream to retrieve archive data from. /// Returns a new suitable for reading from. + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public static TarArchive CreateInputTarArchive(Stream inputStream) + { + return CreateInputTarArchive(inputStream, null); + } + + /// + /// The InputStream based constructors create a TarArchive for the + /// purposes of extracting or listing a tar archive. Thus, use + /// these constructors when you wish to extract files from or list + /// the contents of an existing tar archive. + /// + /// The stream to retrieve archive data from. + /// The used for the Name fields, or null for ASCII only + /// Returns a new suitable for reading from. + public static TarArchive CreateInputTarArchive(Stream inputStream, Encoding nameEncoding) { if (inputStream == null) { @@ -116,7 +131,7 @@ public static TarArchive CreateInputTarArchive(Stream inputStream) } else { - result = CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor); + result = CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor, nameEncoding); } return result; } @@ -127,7 +142,20 @@ public static TarArchive CreateInputTarArchive(Stream inputStream) /// A stream containing the tar archive contents /// The blocking factor to apply /// Returns a suitable for reading. + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor) + { + return CreateInputTarArchive(inputStream, blockFactor, null); + } + + /// + /// Create TarArchive for reading setting block factor + /// + /// A stream containing the tar archive contents + /// The blocking factor to apply + /// The used for the Name fields, or null for ASCII only + /// Returns a suitable for reading. + public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor, Encoding nameEncoding) { if (inputStream == null) { @@ -139,15 +167,15 @@ public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFact throw new ArgumentException("TarInputStream not valid"); } - return new TarArchive(new TarInputStream(inputStream, blockFactor)); + return new TarArchive(new TarInputStream(inputStream, blockFactor, nameEncoding)); } - /// /// Create a TarArchive for writing to, using the default blocking factor /// /// The to write to + /// The used for the Name fields, or null for ASCII only /// Returns a suitable for writing. - public static TarArchive CreateOutputTarArchive(Stream outputStream) + public static TarArchive CreateOutputTarArchive(Stream outputStream, Encoding nameEncoding) { if (outputStream == null) { @@ -163,10 +191,19 @@ public static TarArchive CreateOutputTarArchive(Stream outputStream) } else { - result = CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor); + result = CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor, nameEncoding); } return result; } + /// + /// Create a TarArchive for writing to, using the default blocking factor + /// + /// The to write to + /// Returns a suitable for writing. + public static TarArchive CreateOutputTarArchive(Stream outputStream) + { + return CreateOutputTarArchive(outputStream, null); + } /// /// Create a tar archive for writing. @@ -175,6 +212,17 @@ public static TarArchive CreateOutputTarArchive(Stream outputStream) /// The blocking factor to use for buffering. /// Returns a suitable for writing. public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor) + { + return CreateOutputTarArchive(outputStream, blockFactor, null); + } + /// + /// Create a tar archive for writing. + /// + /// The stream to write to + /// The blocking factor to use for buffering. + /// The used for the Name fields, or null for ASCII only + /// Returns a suitable for writing. + public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor, Encoding nameEncoding) { if (outputStream == null) { @@ -186,7 +234,7 @@ public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFa throw new ArgumentException("TarOutputStream is not valid"); } - return new TarArchive(new TarOutputStream(outputStream, blockFactor)); + return new TarArchive(new TarOutputStream(outputStream, blockFactor, nameEncoding)); } #endregion Static factory methods diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs index f7d2a493d..64a1e5e18 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Text; namespace ICSharpCode.SharpZipLib.Tar { @@ -49,10 +50,25 @@ private TarEntry() /// /// The header bytes from a tar archive entry. /// - public TarEntry(byte[] headerBuffer) + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] + public TarEntry(byte[] headerBuffer) : this(headerBuffer, null) + { + } + + /// + /// Construct an entry from an archive's header bytes. File is set + /// to null. + /// + /// + /// The header bytes from a tar archive entry. + /// + /// + /// The used for the Name fields, or null for ASCII only + /// + public TarEntry(byte[] headerBuffer, Encoding nameEncoding) { header = new TarHeader(); - header.ParseBuffer(headerBuffer); + header.ParseBuffer(headerBuffer, nameEncoding); } /// @@ -469,9 +485,24 @@ public TarEntry[] GetDirectoryEntries() /// /// The tar entry header buffer to fill in. /// + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public void WriteEntryHeader(byte[] outBuffer) { - header.WriteHeader(outBuffer); + WriteEntryHeader(outBuffer, null); + } + + /// + /// Write an entry's header information to a header buffer. + /// + /// + /// The tar entry header buffer to fill in. + /// + /// + /// The used for the Name fields, or null for ASCII only + /// + public void WriteEntryHeader(byte[] outBuffer, Encoding nameEncoding) + { + header.WriteHeader(outBuffer, nameEncoding); } /// @@ -484,9 +515,28 @@ public void WriteEntryHeader(byte[] outBuffer) /// /// The new name to place into the header buffer. /// + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] static public void AdjustEntryName(byte[] buffer, string newName) { - TarHeader.GetNameBytes(newName, buffer, 0, TarHeader.NAMELEN); + AdjustEntryName(buffer, newName, null); + } + + /// + /// Convenience method that will modify an entry's name directly + /// in place in an entry header buffer byte array. + /// + /// + /// The buffer containing the entry header to modify. + /// + /// + /// The new name to place into the header buffer. + /// + /// + /// The used for the Name fields, or null for ASCII only + /// + static public void AdjustEntryName(byte[] buffer, string newName, Encoding nameEncoding) + { + TarHeader.GetNameBytes(newName, buffer, 0, TarHeader.NAMELEN, nameEncoding); } /// diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs b/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs index e29507427..3bd1bdffe 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs @@ -528,7 +528,10 @@ public object Clone() /// /// The tar entry header buffer to get information from. /// - public void ParseBuffer(byte[] header) + /// + /// The used for the Name field, or null for ASCII only + /// + public void ParseBuffer(byte[] header, Encoding nameEncoding) { if (header == null) { @@ -537,7 +540,7 @@ public void ParseBuffer(byte[] header) int offset = 0; - name = ParseName(header, offset, NAMELEN).ToString(); + name = ParseName(header, offset, NAMELEN, nameEncoding).ToString(); offset += NAMELEN; mode = (int)ParseOctal(header, offset, MODELEN); @@ -560,21 +563,21 @@ public void ParseBuffer(byte[] header) TypeFlag = header[offset++]; - LinkName = ParseName(header, offset, NAMELEN).ToString(); + LinkName = ParseName(header, offset, NAMELEN, nameEncoding).ToString(); offset += NAMELEN; - Magic = ParseName(header, offset, MAGICLEN).ToString(); + Magic = ParseName(header, offset, MAGICLEN, nameEncoding).ToString(); offset += MAGICLEN; if (Magic == "ustar") { - Version = ParseName(header, offset, VERSIONLEN).ToString(); + Version = ParseName(header, offset, VERSIONLEN, nameEncoding).ToString(); offset += VERSIONLEN; - UserName = ParseName(header, offset, UNAMELEN).ToString(); + UserName = ParseName(header, offset, UNAMELEN, nameEncoding).ToString(); offset += UNAMELEN; - GroupName = ParseName(header, offset, GNAMELEN).ToString(); + GroupName = ParseName(header, offset, GNAMELEN, nameEncoding).ToString(); offset += GNAMELEN; DevMajor = (int)ParseOctal(header, offset, DEVLEN); @@ -583,18 +586,41 @@ public void ParseBuffer(byte[] header) DevMinor = (int)ParseOctal(header, offset, DEVLEN); offset += DEVLEN; - string prefix = ParseName(header, offset, PREFIXLEN).ToString(); + string prefix = ParseName(header, offset, PREFIXLEN, nameEncoding).ToString(); if (!string.IsNullOrEmpty(prefix)) Name = prefix + '/' + Name; } isChecksumValid = Checksum == TarHeader.MakeCheckSum(header); } + /// + /// Parse TarHeader information from a header buffer. + /// + /// + /// The tar entry header buffer to get information from. + /// + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] + public void ParseBuffer(byte[] header) + { + ParseBuffer(header, null); + } + /// /// 'Write' header information to buffer provided, updating the check sum. /// /// output buffer for header information + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public void WriteHeader(byte[] outBuffer) + { + WriteHeader(outBuffer, null); + } + + /// + /// 'Write' header information to buffer provided, updating the check sum. + /// + /// output buffer for header information + /// The used for the Name field, or null for ASCII only + public void WriteHeader(byte[] outBuffer, Encoding nameEncoding) { if (outBuffer == null) { @@ -603,7 +629,7 @@ public void WriteHeader(byte[] outBuffer) int offset = 0; - offset = GetNameBytes(Name, outBuffer, offset, NAMELEN); + offset = GetNameBytes(Name, outBuffer, offset, NAMELEN, nameEncoding); offset = GetOctalBytes(mode, outBuffer, offset, MODELEN); offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN); offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN); @@ -619,11 +645,11 @@ public void WriteHeader(byte[] outBuffer) outBuffer[offset++] = TypeFlag; - offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN); - offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN); - offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN); - offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN); - offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN); + offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN, nameEncoding); + offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN, nameEncoding); + offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN, nameEncoding); + offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN, nameEncoding); + offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN, nameEncoding); if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK)) { @@ -787,7 +813,31 @@ static public long ParseOctal(byte[] header, int offset, int length) /// /// The name parsed. /// + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] static public StringBuilder ParseName(byte[] header, int offset, int length) + { + return ParseName(header, offset, length, null); + } + + /// + /// Parse a name from a header buffer. + /// + /// + /// The header buffer from which to parse. + /// + /// + /// The offset into the buffer from which to parse. + /// + /// + /// The number of header bytes to parse. + /// + /// + /// name encoding, or null for ASCII only + /// + /// + /// The name parsed. + /// + static public StringBuilder ParseName(byte[] header, int offset, int length, Encoding encoding) { if (header == null) { @@ -811,13 +861,28 @@ static public StringBuilder ParseName(byte[] header, int offset, int length) var result = new StringBuilder(length); - for (int i = offset; i < offset + length; ++i) + int count = 0; + if(encoding == null) { - if (header[i] == 0) + for (int i = offset; i < offset + length; ++i) { - break; + if (header[i] == 0) + { + break; + } + result.Append((char)header[i]); } - result.Append((char)header[i]); + } + else + { + for(int i = offset; i < offset + length; ++i, ++count) + { + if(header[i] == 0) + { + break; + } + } + result.Append(encoding.GetString(header, offset, count)); } return result; @@ -834,17 +899,7 @@ static public StringBuilder ParseName(byte[] header, int offset, int length) /// The next free index in the public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (buffer == null) - { - throw new ArgumentNullException(nameof(buffer)); - } - - return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length); + return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length, null); } /// @@ -857,6 +912,21 @@ public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer /// The number of characters/bytes to add /// The next free index in the public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length) + { + return GetNameBytes(name, nameOffset, buffer, bufferOffset, length, null); + } + + /// + /// Add name to the buffer as a collection of bytes + /// + /// The name to add + /// The offset of the first character + /// The buffer to add to + /// The index of the first byte to add + /// The number of characters/bytes to add + /// name encoding, or null for ASCII only + /// The next free index in the + public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length, Encoding encoding) { if (name == null) { @@ -869,20 +939,29 @@ public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int b } int i; - - for (i = 0; i < length && nameOffset + i < name.Length; ++i) + if(encoding != null) { - buffer[bufferOffset + i] = (byte)name[nameOffset + i]; + // it can be more sufficient if using Span or unsafe + var nameArray = name.ToCharArray(nameOffset, Math.Min(name.Length - nameOffset, length)); + // it can be more sufficient if using Span(or unsafe?) and ArrayPool for temporary buffer + var bytes = encoding.GetBytes(nameArray, 0, nameArray.Length); + i = Math.Min(bytes.Length, length); + Array.Copy(bytes, 0, buffer, bufferOffset, i); + } + else + { + for (i = 0; i < length && nameOffset + i < name.Length; ++i) + { + buffer[bufferOffset + i] = (byte)name[nameOffset + i]; + } } for (; i < length; ++i) { buffer[bufferOffset + i] = 0; } - return bufferOffset + length; } - /// /// Add an entry name to the buffer /// @@ -901,7 +980,34 @@ public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int b /// /// The index of the next free byte in the buffer /// + /// TODO: what should be default behavior?(omit upper byte or UTF8?) + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length) + { + return GetNameBytes(name, buffer, offset, length, null); + } + + /// + /// Add an entry name to the buffer + /// + /// + /// The name to add + /// + /// + /// The buffer to add to + /// + /// + /// The offset into the buffer from which to start adding + /// + /// + /// The number of header bytes to add + /// + /// + /// + /// + /// The index of the next free byte in the buffer + /// + public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length, Encoding encoding) { if (name == null) { @@ -913,7 +1019,7 @@ public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, in throw new ArgumentNullException(nameof(buffer)); } - return GetNameBytes(name.ToString(), 0, buffer, offset, length); + return GetNameBytes(name.ToString(), 0, buffer, offset, length, encoding); } /// @@ -924,7 +1030,23 @@ public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, in /// The offset into the buffer from which to start adding /// The number of header bytes to add /// The index of the next free byte in the buffer + /// TODO: what should be default behavior?(omit upper byte or UTF8?) + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public static int GetNameBytes(string name, byte[] buffer, int offset, int length) + { + return GetNameBytes(name, buffer, offset, length, null); + } + + /// + /// Add an entry name to the buffer + /// + /// The name to add + /// The buffer to add to + /// The offset into the buffer from which to start adding + /// The number of header bytes to add + /// + /// The index of the next free byte in the buffer + public static int GetNameBytes(string name, byte[] buffer, int offset, int length, Encoding encoding) { if (name == null) { @@ -936,9 +1058,8 @@ public static int GetNameBytes(string name, byte[] buffer, int offset, int lengt throw new ArgumentNullException(nameof(buffer)); } - return GetNameBytes(name, 0, buffer, offset, length); + return GetNameBytes(name, 0, buffer, offset, length, encoding); } - /// /// Add a string to a buffer as a collection of ascii bytes. /// @@ -948,7 +1069,23 @@ public static int GetNameBytes(string name, byte[] buffer, int offset, int lengt /// The offset to start adding at. /// The number of ascii characters to add. /// The next free index in the buffer. + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length) + { + return GetAsciiBytes(toAdd, nameOffset, buffer, bufferOffset, length, null); + } + + /// + /// Add a string to a buffer as a collection of ascii bytes. + /// + /// The string to add + /// The offset of the first character to add. + /// The buffer to add to. + /// The offset to start adding at. + /// The number of ascii characters to add. + /// String encoding, or null for ASCII only + /// The next free index in the buffer. + public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length, Encoding encoding) { if (toAdd == null) { @@ -961,9 +1098,21 @@ public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int } int i; - for (i = 0; i < length && nameOffset + i < toAdd.Length; ++i) + if(encoding == null) + { + for (i = 0; i < length && nameOffset + i < toAdd.Length; ++i) + { + buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i]; + } + } + else { - buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i]; + // It can be more sufficient if using unsafe code or Span(ToCharArray can be omitted) + var chars = toAdd.ToCharArray(); + // It can be more sufficient if using Span(or unsafe?) and ArrayPool for temporary buffer + var bytes = encoding.GetBytes(chars, nameOffset, Math.Min(toAdd.Length - nameOffset, length)); + i = Math.Min(bytes.Length, length); + Array.Copy(bytes, 0, buffer, bufferOffset, i); } // If length is beyond the toAdd string length (which is OK by the prev loop condition), eg if a field has fixed length and the string is shorter, make sure all of the extra chars are written as NULLs, so that the reader func would ignore them and get back the original string for (; i < length; ++i) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs b/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs index 3c0cd96cd..078ff0a0f 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs @@ -18,8 +18,18 @@ public class TarInputStream : Stream /// Construct a TarInputStream with default block factor /// /// stream to source data from + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public TarInputStream(Stream inputStream) - : this(inputStream, TarBuffer.DefaultBlockFactor) + : this(inputStream, TarBuffer.DefaultBlockFactor, null) + { + } + /// + /// Construct a TarInputStream with default block factor + /// + /// stream to source data from + /// The used for the Name fields, or null for ASCII only + public TarInputStream(Stream inputStream, Encoding nameEncoding) + : this(inputStream, TarBuffer.DefaultBlockFactor, nameEncoding) { } @@ -28,10 +38,25 @@ public TarInputStream(Stream inputStream) /// /// stream to source data from /// block factor to apply to archive + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public TarInputStream(Stream inputStream, int blockFactor) { this.inputStream = inputStream; tarBuffer = TarBuffer.CreateInputTarBuffer(inputStream, blockFactor); + encoding = null; + } + + /// + /// Construct a TarInputStream with user specified block factor + /// + /// stream to source data from + /// block factor to apply to archive + /// The used for the Name fields, or null for ASCII only + public TarInputStream(Stream inputStream, int blockFactor, Encoding nameEncoding) + { + this.inputStream = inputStream; + tarBuffer = TarBuffer.CreateInputTarBuffer(inputStream, blockFactor); + encoding = nameEncoding; } #endregion Constructors @@ -452,7 +477,7 @@ public TarEntry GetNextEntry() try { var header = new TarHeader(); - header.ParseBuffer(headerBuf); + header.ParseBuffer(headerBuf, encoding); if (!header.IsChecksumValid) { throw new TarException("Header checksum is invalid"); @@ -478,7 +503,7 @@ public TarEntry GetNextEntry() throw new InvalidHeaderException("Failed to read long name entry"); } - longName.Append(TarHeader.ParseName(nameBuffer, 0, numRead).ToString()); + longName.Append(TarHeader.ParseName(nameBuffer, 0, numRead, encoding).ToString()); numToRead -= numRead; } @@ -538,7 +563,7 @@ public TarEntry GetNextEntry() if (entryFactory == null) { - currentEntry = new TarEntry(headerBuf); + currentEntry = new TarEntry(headerBuf, encoding); if (longName != null) { currentEntry.Name = longName.ToString(); @@ -611,6 +636,8 @@ private void SkipToNextEntry() /// public interface IEntryFactory { + // This interface does not considering name encoding. + // How this interface should be? /// /// Create an entry based on name alone /// @@ -648,6 +675,22 @@ public interface IEntryFactory /// public class EntryFactoryAdapter : IEntryFactory { + Encoding nameEncoding; + /// + /// Construct standard entry factory class with ASCII name encoding + /// + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] + public EntryFactoryAdapter() + { + } + /// + /// Construct standard entry factory with name encoding + /// + /// The used for the Name fields, or null for ASCII only + public EntryFactoryAdapter(Encoding nameEncoding) + { + this.nameEncoding = nameEncoding; + } /// /// Create a based on named /// @@ -675,7 +718,7 @@ public TarEntry CreateEntryFromFile(string fileName) /// A new public TarEntry CreateEntry(byte[] headerBuffer) { - return new TarEntry(headerBuffer); + return new TarEntry(headerBuffer, nameEncoding); } } @@ -721,6 +764,8 @@ public TarEntry CreateEntry(byte[] headerBuffer) /// private readonly Stream inputStream; + private readonly Encoding encoding; + #endregion Instance Fields } } diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs b/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs index 09202caa7..6efcf3a93 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Text; namespace ICSharpCode.SharpZipLib.Tar { @@ -17,16 +18,28 @@ public class TarOutputStream : Stream /// Construct TarOutputStream using default block factor /// /// stream to write to + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public TarOutputStream(Stream outputStream) : this(outputStream, TarBuffer.DefaultBlockFactor) { } + /// + /// Construct TarOutputStream using default block factor + /// + /// stream to write to + /// The used for the Name fields, or null for ASCII only + public TarOutputStream(Stream outputStream, Encoding nameEncoding) + : this(outputStream, TarBuffer.DefaultBlockFactor, nameEncoding) + { + } + /// /// Construct TarOutputStream with user specified block factor /// /// stream to write to /// blocking factor + [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] public TarOutputStream(Stream outputStream, int blockFactor) { if (outputStream == null) @@ -41,6 +54,28 @@ public TarOutputStream(Stream outputStream, int blockFactor) blockBuffer = new byte[TarBuffer.BlockSize]; } + /// + /// Construct TarOutputStream with user specified block factor + /// + /// stream to write to + /// blocking factor + /// The used for the Name fields, or null for ASCII only + public TarOutputStream(Stream outputStream, int blockFactor, Encoding nameEncoding) + { + if (outputStream == null) + { + throw new ArgumentNullException(nameof(outputStream)); + } + + this.outputStream = outputStream; + buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); + + assemblyBuffer = new byte[TarBuffer.BlockSize]; + blockBuffer = new byte[TarBuffer.BlockSize]; + + this.nameEncoding = nameEncoding; + } + #endregion Constructors /// @@ -241,7 +276,9 @@ public void PutNextEntry(TarEntry entry) throw new ArgumentNullException(nameof(entry)); } - if (entry.TarHeader.Name.Length > TarHeader.NAMELEN) + var namelen = nameEncoding != null ? nameEncoding.GetByteCount(entry.TarHeader.Name) : entry.TarHeader.Name.Length; + + if (namelen > TarHeader.NAMELEN) { var longHeader = new TarHeader(); longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME; @@ -252,23 +289,23 @@ public void PutNextEntry(TarEntry entry) longHeader.GroupName = entry.GroupName; longHeader.UserName = entry.UserName; longHeader.LinkName = ""; - longHeader.Size = entry.TarHeader.Name.Length + 1; // Plus one to avoid dropping last char + longHeader.Size = namelen + 1; // Plus one to avoid dropping last char - longHeader.WriteHeader(blockBuffer); + longHeader.WriteHeader(blockBuffer, nameEncoding); buffer.WriteBlock(blockBuffer); // Add special long filename header block int nameCharIndex = 0; - while (nameCharIndex < entry.TarHeader.Name.Length + 1 /* we've allocated one for the null char, now we must make sure it gets written out */) + while (nameCharIndex < namelen + 1 /* we've allocated one for the null char, now we must make sure it gets written out */) { Array.Clear(blockBuffer, 0, blockBuffer.Length); - TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize); // This func handles OK the extra char out of string length + TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize, nameEncoding); // This func handles OK the extra char out of string length nameCharIndex += TarBuffer.BlockSize; buffer.WriteBlock(blockBuffer); } } - entry.WriteEntryHeader(blockBuffer); + entry.WriteEntryHeader(blockBuffer, nameEncoding); buffer.WriteBlock(blockBuffer); currBytes = 0; @@ -475,6 +512,11 @@ private void WriteEofBlock() /// protected Stream outputStream; + /// + /// name encoding + /// + protected Encoding nameEncoding; + #endregion Instance Fields } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs index 69e0936bc..5cdd9404e 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs @@ -4,6 +4,7 @@ using NUnit.Framework; using System; using System.IO; +using System.Text; namespace ICSharpCode.SharpZipLib.Tests.Tar { @@ -20,6 +21,12 @@ private void EntryCounter(TarArchive archive, TarEntry entry, string message) entryCount++; } + [SetUp] + public void Setup() + { + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + /// /// Test that an empty archive can be created and when read has 0 entries in it /// @@ -41,7 +48,7 @@ public void EmptyTar() ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); - using (TarArchive tarIn = TarArchive.CreateInputTarArchive(ms2)) + using (TarArchive tarIn = TarArchive.CreateInputTarArchive(ms2, null)) { entryCount = 0; tarIn.ProgressMessageEvent += EntryCounter; @@ -65,7 +72,7 @@ public void BlockFactorHandling() { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms, factor)) + using (TarOutputStream tarOut = new TarOutputStream(ms, factor, null)) { TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); entry.Size = (TarBuffer.BlockSize * factor * FillFactor); @@ -126,7 +133,7 @@ public void TrailerContainsNulls() { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms, TestBlockFactor)) + using (TarOutputStream tarOut = new TarOutputStream(ms, TestBlockFactor, null)) { TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); if (iteration > 0) @@ -188,7 +195,7 @@ public void TrailerContainsNulls() private void TryLongName(string name) { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms)) + using (TarOutputStream tarOut = new TarOutputStream(ms, null)) { DateTime modTime = DateTime.Now; @@ -200,7 +207,7 @@ private void TryLongName(string name) ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); - using (TarInputStream tarIn = new TarInputStream(ms2)) + using (TarInputStream tarIn = new TarInputStream(ms2, null)) { TarEntry nextEntry = tarIn.GetNextEntry(); @@ -286,7 +293,7 @@ public void ExtendedHeaderLongName() truncated = null; using (var ms = new MemoryStream(buffer)) - using (var tis = new TarInputStream(ms)) + using (var tis = new TarInputStream(ms, null)) { var entry = tis.GetNextEntry(); Assert.IsNotNull(entry, "Entry is null"); @@ -387,7 +394,7 @@ public void HeaderEquality() public void Checksum() { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms)) + using (TarOutputStream tarOut = new TarOutputStream(ms, null)) { DateTime modTime = DateTime.Now; @@ -402,7 +409,7 @@ public void Checksum() ms2.Seek(0, SeekOrigin.Begin); TarEntry nextEntry; - using (TarInputStream tarIn = new TarInputStream(ms2)) + using (TarInputStream tarIn = new TarInputStream(ms2, null)) { nextEntry = tarIn.GetNextEntry(); Assert.IsTrue(nextEntry.TarHeader.IsChecksumValid, "Checksum should be valid"); @@ -414,7 +421,7 @@ public void Checksum() ms3.Write(new byte[] { 34 }, 0, 1); ms3.Seek(0, SeekOrigin.Begin); - using (TarInputStream tarIn = new TarInputStream(ms3)) + using (TarInputStream tarIn = new TarInputStream(ms3, null)) { bool trapped = false; @@ -442,7 +449,7 @@ public void ValuesPreserved() TarEntry entry; DateTime modTime = DateTime.Now; - using (TarOutputStream tarOut = new TarOutputStream(ms)) + using (TarOutputStream tarOut = new TarOutputStream(ms, null)) { entry = TarEntry.CreateTarEntry("TestEntry"); entry.GroupId = 12; @@ -459,7 +466,7 @@ public void ValuesPreserved() ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); - using (TarInputStream tarIn = new TarInputStream(ms2)) + using (TarInputStream tarIn = new TarInputStream(ms2, null)) { TarEntry nextEntry = tarIn.GetNextEntry(); Assert.AreEqual(entry.TarHeader.Checksum, nextEntry.TarHeader.Checksum, "Checksum"); @@ -637,7 +644,7 @@ public void CloningAndUniqueness() public void OutputStreamOwnership() { var memStream = new TrackedMemoryStream(); - var s = new TarOutputStream(memStream); + var s = new TarOutputStream(memStream, null); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); @@ -648,7 +655,7 @@ public void OutputStreamOwnership() Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close"); memStream = new TrackedMemoryStream(); - s = new TarOutputStream(memStream); + s = new TarOutputStream(memStream, null); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); @@ -665,7 +672,7 @@ public void OutputStreamOwnership() public void InputStreamOwnership() { var memStream = new TrackedMemoryStream(); - var s = new TarInputStream(memStream); + var s = new TarInputStream(memStream, null); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); @@ -676,7 +683,7 @@ public void InputStreamOwnership() Assert.IsTrue(memStream.IsDisposed, "Should be disposed after parent owner close"); memStream = new TrackedMemoryStream(); - s = new TarInputStream(memStream); + s = new TarInputStream(memStream, null); Assert.IsFalse(memStream.IsClosed, "Shouldnt be closed initially"); Assert.IsFalse(memStream.IsDisposed, "Shouldnt be disposed initially"); @@ -708,7 +715,7 @@ public void EndBlockHandling() outCount = ms.Position; ms.Seek(0, SeekOrigin.Begin); - using (var tarIn = TarArchive.CreateInputTarArchive(ms)) + using (var tarIn = TarArchive.CreateInputTarArchive(ms, null)) using (var tempDir = new Utils.TempDir()) { tarIn.IsStreamOwner = false; @@ -739,7 +746,7 @@ public void WriteThroughput() PerformanceTesting.TestWrite(TestDataSize.Large, bs => { - var tos = new TarOutputStream(bs); + var tos = new TarOutputStream(bs, null); tos.PutNextEntry(new TarEntry(new TarHeader() { Name = EntryName, @@ -766,7 +773,7 @@ public void SingleLargeEntry() size: dataSize, input: bs => { - var tis = new TarInputStream(bs); + var tis = new TarInputStream(bs, null); var entry = tis.GetNextEntry(); Assert.AreEqual(EntryName, entry.Name); @@ -774,7 +781,7 @@ public void SingleLargeEntry() }, output: bs => { - var tos = new TarOutputStream(bs); + var tos = new TarOutputStream(bs, null); tos.PutNextEntry(new TarEntry(new TarHeader() { Name = EntryName, @@ -823,7 +830,7 @@ public void ExtractingCorruptTarShouldntLeakFiles() { tempDirName = tempDir.Fullpath; - using (var tarIn = TarArchive.CreateInputTarArchive(gzipStream)) + using (var tarIn = TarArchive.CreateInputTarArchive(gzipStream, null)) { tarIn.IsStreamOwner = false; Assert.Throws(() => tarIn.ExtractContents(tempDir.Fullpath)); @@ -831,7 +838,65 @@ public void ExtractingCorruptTarShouldntLeakFiles() } Assert.That(Directory.Exists(tempDirName), Is.False, "Temporary folder should have been removed"); - } + } + } + } + [TestCase(10, "utf-8")] + [TestCase(10, "shift-jis")] + [Category("Tar")] + public void ParseHeaderWithEncoding(int length, string encodingName) + { + // U+3042 is Japanese Hiragana + // https://unicode.org/charts/PDF/U3040.pdf + var name = new string((char)0x3042, length); + var header = new TarHeader(); + var enc = Encoding.GetEncoding(encodingName); + byte[] headerbytes = new byte[1024]; + var encodedName = enc.GetBytes(name); + header.Name = name; + header.WriteHeader(headerbytes, enc); + var reparseHeader = new TarHeader(); + reparseHeader.ParseBuffer(headerbytes, enc); + Assert.AreEqual(name, reparseHeader.Name); + // top 100 bytes are name field in tar header + for (int i = 0;i < encodedName.Length;i++) + { + Assert.AreEqual(encodedName[i], headerbytes[i]); + } + } + [TestCase(1, "utf-8")] + [TestCase(100, "utf-8")] + [TestCase(128, "utf-8")] + [TestCase(1, "shift-jis")] + [TestCase(100, "shift-jis")] + [TestCase(128, "shift-jis")] + [Category("Tar")] + public void StreamWithJapaneseName(int length, string encodingName) + { + // U+3042 is Japanese Hiragana + // https://unicode.org/charts/PDF/U3040.pdf + var entryName = new string((char)0x3042, length); + var data = new byte[32]; + var encoding = Encoding.GetEncoding(encodingName); + using(var memoryStream = new MemoryStream()) + { + using(var tarOutput = new TarOutputStream(memoryStream, encoding)) + { + var entry = TarEntry.CreateTarEntry(entryName); + entry.Size = 32; + tarOutput.PutNextEntry(entry); + tarOutput.Write(data, 0, data.Length); + } + using(var memInput = new MemoryStream(memoryStream.ToArray())) + using(var inputStream = new TarInputStream(memInput, encoding)) + { + var buf = new byte[64]; + var entry = inputStream.GetNextEntry(); + Assert.AreEqual(entryName, entry.Name); + var bytesread = inputStream.Read(buf, 0, buf.Length); + Assert.AreEqual(data.Length, bytesread); + } + File.WriteAllBytes(Path.Combine(Path.GetTempPath(), $"jpnametest_{length}_{encodingName}.tar"), memoryStream.ToArray()); } } } From 73aa23a7f59af28056252c25f24c1cefe622f91c Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 21:38:42 +0100 Subject: [PATCH 013/162] Merge PR #472: Allow ZipFile to accept empty strings as passwords when decrypting AES entries * Add unit test for reading an AES encrypted entry with an empty password * Allow ZipFile to accept empty strings as passwords when decrypting AES entries --- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 7 ++-- .../Zip/ZipEncryptionHandling.cs | 34 +++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 6cacf2da8..091a98d53 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -367,9 +367,10 @@ public string Password } else { - rawPassword_ = value; key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(value)); } + + rawPassword_ = value; } } @@ -3612,9 +3613,9 @@ private Stream CreateAndInitDecryptionStream(Stream baseStream, ZipEntry entry) { if (entry.Version >= ZipConstants.VERSION_AES) { - // + // Issue #471 - accept an empty string as a password, but reject null. OnKeysRequired(entry.Name); - if (HaveKeys == false) + if (rawPassword_ == null) { throw new ZipException("No password available for AES encrypted stream"); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index 6b14cad2c..f9c988df1 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -365,6 +365,40 @@ public void ZipFileAesDelete() } } + // This is a zip file with one AES encrypted entry, whose password in an empty string. + const string TestFileWithEmptyPassword = @"UEsDBDMACQBjACaj0FAyKbop//////////8EAB8AdGVzdAEAEAA4AAAA + AAAAAFIAAAAAAAAAAZkHAAIAQUUDCABADvo3YqmCtIE+lhw26kjbqkGsLEOk6bVA+FnSpVD4yGP4Mr66Hs14aTtsPUaANX2 + Z6qZczEmwoaNQpNBnKl7p9YOG8GSHDfTCUU/AZvT4yGFhUEsHCDIpuilSAAAAAAAAADgAAAAAAAAAUEsBAjMAMwAJAGMAJq + PQUDIpuin//////////wQAHwAAAAAAAAAAAAAAAAAAAHRlc3QBABAAOAAAAAAAAABSAAAAAAAAAAGZBwACAEFFAwgAUEsFBgAAAAABAAEAUQAAAKsAAAAAAA=="; + + /// + /// Test reading an AES encrypted entry whose password is an empty string. + /// + /// + /// Test added for https://github.com/icsharpcode/SharpZipLib/issues/471. + /// + [Test] + [Category("Zip")] + public void ZipFileAESReadWithEmptyPassword() + { + var fileBytes = Convert.FromBase64String(TestFileWithEmptyPassword); + + using (var ms = new MemoryStream(fileBytes)) + using (var zipFile = new ZipFile(ms, leaveOpen: true)) + { + zipFile.Password = string.Empty; + + var entry = zipFile.FindEntry("test", true); + + using (var inputStream = zipFile.GetInputStream(entry)) + using (var sr = new StreamReader(inputStream, Encoding.UTF8)) + { + var content = sr.ReadToEnd(); + Assert.That(content, Is.EqualTo("Lorem ipsum dolor sit amet, consectetur adipiscing elit."), "Decompressed content does not match expected data"); + } + } + } + private static readonly string[] possible7zPaths = new[] { // Check in PATH "7z", "7za", From 1a130a0c88ecbf8edb039edb4ffdb333834fbf11 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 22:17:34 +0100 Subject: [PATCH 014/162] Merge PR #390: Override Ensure GZipOutputStream headers are written before flush * Add unit tests to repro #382 * Add an override of Flush() to GZipOutputStream to ensure the headers is writen before flushing --- .../GZip/GzipOutputStream.cs | 14 +++++ .../GZip/GZipTests.cs | 63 +++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs index 3079b04aa..afa43d7fd 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs @@ -160,6 +160,20 @@ protected override void Dispose(bool disposing) } } + /// + /// Flushes the stream by ensuring the header is written, and then calling Flush + /// on the deflater. + /// + public override void Flush() + { + if (state_ == OutputState.Header) + { + WriteHeader(); + } + + base.Flush(); + } + #endregion Stream overrides #region DeflaterOutputStream overrides diff --git a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs index ef63c2997..5846b0d5b 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs @@ -76,6 +76,37 @@ public void DelayedHeaderWriteNoData() Assert.IsTrue(data.Length > 0); } + + /// + /// Variant of DelayedHeaderWriteNoData testing flushing for https://github.com/icsharpcode/SharpZipLib/issues/382 + /// + [Test] + [Category("GZip")] + public void DelayedHeaderWriteFlushNoData() + { + var ms = new MemoryStream(); + Assert.AreEqual(0, ms.Length); + + using (GZipOutputStream outStream = new GZipOutputStream(ms) { IsStreamOwner = false }) + { + // #382 - test flushing the stream before writing to it. + outStream.Flush(); + } + + ms.Seek(0, SeekOrigin.Begin); + + // Test that the gzip stream can be read + var readStream = new MemoryStream(); + using (GZipInputStream inStream = new GZipInputStream(ms)) + { + inStream.CopyTo(readStream); + } + + byte[] data = readStream.ToArray(); + + Assert.That(data, Is.Empty, "Should not have any decompressed data"); + } + /// /// Writing GZip headers is delayed so that this stream can be used with HTTP/IIS. /// @@ -99,6 +130,38 @@ public void DelayedHeaderWriteWithData() Assert.IsTrue(data.Length > 0); } + /// + /// variant of DelayedHeaderWriteWithData to test https://github.com/icsharpcode/SharpZipLib/issues/382 + /// + [Test] + [Category("GZip")] + public void DelayedHeaderWriteFlushWithData() + { + var ms = new MemoryStream(); + Assert.AreEqual(0, ms.Length); + using (GZipOutputStream outStream = new GZipOutputStream(ms) { IsStreamOwner = false }) + { + Assert.AreEqual(0, ms.Length); + + // #382 - test flushing the stream before writing to it. + outStream.Flush(); + outStream.WriteByte(45); + } + + ms.Seek(0, SeekOrigin.Begin); + + // Test that the gzip stream can be read + var readStream = new MemoryStream(); + using (GZipInputStream inStream = new GZipInputStream(ms)) + { + inStream.CopyTo(readStream); + } + + // Check that the data was read + byte[] data = readStream.ToArray(); + CollectionAssert.AreEqual(new byte[] { 45 }, data, "Decompressed data should match initial data"); + } + [Test] [Category("GZip")] public void ZeroLengthInputStream() From d506c555c928b21c5e1a8fd04f47c7a2c995eab6 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 22:20:35 +0100 Subject: [PATCH 015/162] Merge PR #435: Add unit test for ZipFile.Add(string fileName, string entryName) --- .../Zip/ZipFileHandling.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index c79137130..996b09213 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -1569,5 +1569,47 @@ public void AddingAnAESEncryptedEntryShouldThrow() Assert.That(exception.Message, Is.EqualTo("Creation of AES encrypted entries is not supported")); } } + + /// + /// Test that we can add a file entry and set the name to sometihng other than the name of the file. + /// + [Test] + [Category("Zip")] + [Category("CreatesTempFile")] + public void AddFileWithAlternateName() + { + // Create a unique name that will be different from the file name + string fileName = Guid.NewGuid().ToString(); + + using (var sourceFile = Utils.GetDummyFile()) + using (var outputFile = Utils.GetDummyFile(0)) + { + var inputContent = File.ReadAllText(sourceFile.Filename); + using (ZipFile f = ZipFile.Create(outputFile.Filename)) + { + f.BeginUpdate(); + + // Add a file with the unique display name + f.Add(sourceFile.Filename, fileName); + + f.CommitUpdate(); + f.Close(); + } + + using (ZipFile zipFile = new ZipFile(outputFile.Filename)) + { + Assert.That(zipFile.Count, Is.EqualTo(1)); + + var fileEntry = zipFile.GetEntry(fileName); + Assert.That(fileEntry, Is.Not.Null); + + using (var sr = new StreamReader(zipFile.GetInputStream(fileEntry))) + { + var outputContent = sr.ReadToEnd(); + Assert.AreEqual(inputContent, outputContent, "extracted content does not match source content"); + } + } + } + } } } From 23841d246d52480344a37f93d5fad7f3ceaa1c69 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 22:21:27 +0100 Subject: [PATCH 016/162] Merge PR #433: Restore directory timestamps when extracting with FastZip * When extracting folders with FastZip, reset the last modified time if the RestoreDateTimeOnExtract option is enabled * Add unit test for restoring directory timestamps when extracing with fastzip and RestoreDateTimeOnExtract is true --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 5 ++ .../Zip/FastZipHandling.cs | 57 +++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 319645a5b..2e1719e88 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -708,6 +708,11 @@ private void ExtractEntry(ZipEntry entry) try { Directory.CreateDirectory(dirName); + + if (entry.IsDirectory && restoreDateTimeOnExtract_) + { + Directory.SetLastWriteTime(dirName, entry.DateTime); + } } catch (Exception ex) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index b1a0eb100..67b481f65 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -568,5 +568,62 @@ public void StreamClosedOnError() // test folder should not have been created on error Assert.That(Directory.Exists(tempFolderPath), Is.False, "Temp folder path should still not exist"); } + + /// + /// #426 - set the modified date for created directory entries if the RestoreDateTimeOnExtract option is enabled + /// + [Test] + [Category("Zip")] + [Category("CreatesTempFile")] + public void SetDirectoryModifiedDate() + { + string tempFilePath = GetTempFilePath(); + Assert.IsNotNull(tempFilePath, "No permission to execute this test?"); + + string zipName = Path.Combine(tempFilePath, $"{nameof(SetDirectoryModifiedDate)}.zip"); + + EnsureTestDirectoryIsEmpty(tempFilePath); + + var modifiedTime = new DateTime(2001, 1, 2); + string targetDir = Path.Combine(tempFilePath, ZipTempDir, nameof(SetDirectoryModifiedDate)); + using (FileStream fs = File.Create(zipName)) + { + using (ZipOutputStream zOut = new ZipOutputStream(fs)) + { + // Add an empty directory entry, with a specified time field + var entry = new ZipEntry("emptyFolder/") + { + DateTime = modifiedTime + }; + zOut.PutNextEntry(entry); + } + } + + try + { + // extract the zip + var fastZip = new FastZip + { + CreateEmptyDirectories = true, + RestoreDateTimeOnExtract = true + }; + fastZip.ExtractZip(zipName, targetDir, "zz"); + + File.Delete(zipName); + + // Check that the empty sub folder exists and has the expected modlfied date + string emptyTargetDir = Path.Combine(targetDir, "emptyFolder"); + + Assert.That(Directory.Exists(emptyTargetDir), Is.True, "Empty directory should be created"); + + var extractedFolderTime = Directory.GetLastWriteTime(emptyTargetDir); + Assert.That(extractedFolderTime, Is.EqualTo(modifiedTime)); + } + finally + { + // Tidy up + Directory.Delete(targetDir, true); + } + } } } From 274df70bacef9c5873972f89b984ccab325a6ca1 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 23:26:53 +0100 Subject: [PATCH 017/162] PR #450: Fix CA1200 code analyzer warnings --- .../Core/NameFilter.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 88 +++++++++---------- 2 files changed, 45 insertions(+), 45 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Core/NameFilter.cs b/src/ICSharpCode.SharpZipLib/Core/NameFilter.cs index 58c578a25..57751891c 100644 --- a/src/ICSharpCode.SharpZipLib/Core/NameFilter.cs +++ b/src/ICSharpCode.SharpZipLib/Core/NameFilter.cs @@ -106,7 +106,7 @@ public static bool IsValidFilterExpression(string toTest) /// Split a string into its component pieces /// /// The original string - /// Returns an array of values containing the individual filter elements. + /// Returns an array of values containing the individual filter elements. public static string[] SplitQuoted(string original) { char escape = '\\'; diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 091a98d53..59ba3f950 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -4004,12 +4004,12 @@ public override long Position /// /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. /// - /// The sum of offset and count is larger than the buffer length. - /// Methods were called after the stream was closed. - /// The stream does not support reading. - /// buffer is null. - /// An I/O error occurs. - /// offset or count is negative. + /// The sum of offset and count is larger than the buffer length. + /// Methods were called after the stream was closed. + /// The stream does not support reading. + /// buffer is null. + /// An I/O error occurs. + /// offset or count is negative. public override int Read(byte[] buffer, int offset, int count) { return 0; @@ -4019,13 +4019,13 @@ public override int Read(byte[] buffer, int offset, int count) /// Sets the position within the current stream. /// /// A byte offset relative to the origin parameter. - /// A value of type indicating the reference point used to obtain the new position. + /// A value of type indicating the reference point used to obtain the new position. /// /// The new position within the current stream. /// - /// An I/O error occurs. - /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. - /// Methods were called after the stream was closed. + /// An I/O error occurs. + /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. + /// Methods were called after the stream was closed. public override long Seek(long offset, SeekOrigin origin) { return 0; @@ -4035,9 +4035,9 @@ public override long Seek(long offset, SeekOrigin origin) /// Sets the length of the current stream. /// /// The desired length of the current stream in bytes. - /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. - /// An I/O error occurs. - /// Methods were called after the stream was closed. + /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. + /// An I/O error occurs. + /// Methods were called after the stream was closed. public override void SetLength(long value) { } @@ -4048,12 +4048,12 @@ public override void SetLength(long value) /// An array of bytes. This method copies count bytes from buffer to the current stream. /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. /// The number of bytes to be written to the current stream. - /// An I/O error occurs. - /// The stream does not support writing. - /// Methods were called after the stream was closed. - /// buffer is null. - /// The sum of offset and count is greater than the buffer length. - /// offset or count is negative. + /// An I/O error occurs. + /// The stream does not support writing. + /// Methods were called after the stream was closed. + /// buffer is null. + /// The sum of offset and count is greater than the buffer length. + /// offset or count is negative. public override void Write(byte[] buffer, int offset, int count) { baseStream_.Write(buffer, offset, count); @@ -4133,12 +4133,12 @@ public override int ReadByte() /// /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. /// - /// The sum of offset and count is larger than the buffer length. - /// Methods were called after the stream was closed. - /// The stream does not support reading. - /// buffer is null. - /// An I/O error occurs. - /// offset or count is negative. + /// The sum of offset and count is larger than the buffer length. + /// Methods were called after the stream was closed. + /// The stream does not support reading. + /// buffer is null. + /// An I/O error occurs. + /// offset or count is negative. public override int Read(byte[] buffer, int offset, int count) { lock (baseStream_) @@ -4172,12 +4172,12 @@ public override int Read(byte[] buffer, int offset, int count) /// An array of bytes. This method copies count bytes from buffer to the current stream. /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. /// The number of bytes to be written to the current stream. - /// An I/O error occurs. - /// The stream does not support writing. - /// Methods were called after the stream was closed. - /// buffer is null. - /// The sum of offset and count is greater than the buffer length. - /// offset or count is negative. + /// An I/O error occurs. + /// The stream does not support writing. + /// Methods were called after the stream was closed. + /// buffer is null. + /// The sum of offset and count is greater than the buffer length. + /// offset or count is negative. public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); @@ -4187,9 +4187,9 @@ public override void Write(byte[] buffer, int offset, int count) /// When overridden in a derived class, sets the length of the current stream. /// /// The desired length of the current stream in bytes. - /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. - /// An I/O error occurs. - /// Methods were called after the stream was closed. + /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. + /// An I/O error occurs. + /// Methods were called after the stream was closed. public override void SetLength(long value) { throw new NotSupportedException(); @@ -4199,13 +4199,13 @@ public override void SetLength(long value) /// When overridden in a derived class, sets the position within the current stream. /// /// A byte offset relative to the origin parameter. - /// A value of type indicating the reference point used to obtain the new position. + /// A value of type indicating the reference point used to obtain the new position. /// /// The new position within the current stream. /// - /// An I/O error occurs. - /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. - /// Methods were called after the stream was closed. + /// An I/O error occurs. + /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. + /// Methods were called after the stream was closed. public override long Seek(long offset, SeekOrigin origin) { long newPos = readPos_; @@ -4241,7 +4241,7 @@ public override long Seek(long offset, SeekOrigin origin) /// /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// - /// An I/O error occurs. + /// An I/O error occurs. public override void Flush() { // Nothing to do. @@ -4252,9 +4252,9 @@ public override void Flush() /// /// /// The current position within the stream. - /// An I/O error occurs. - /// The stream does not support seeking. - /// Methods were called after the stream was closed. + /// An I/O error occurs. + /// The stream does not support seeking. + /// Methods were called after the stream was closed. public override long Position { get { return readPos_ - start_; } @@ -4280,8 +4280,8 @@ public override long Position /// /// /// A long value representing the length of the stream in bytes. - /// A class derived from Stream does not support seeking. - /// Methods were called after the stream was closed. + /// A class derived from Stream does not support seeking. + /// Methods were called after the stream was closed. public override long Length { get { return length_; } From ca33534a763163fb7c4564521c3330a1044d6ea7 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 23:28:15 +0100 Subject: [PATCH 018/162] PR #445: Make InvalidHeaderException serializable --- .../Tar/InvalidHeaderException.cs | 18 ++++++++++++++++++ .../Serialization/SerializationTests.cs | 1 + 2 files changed, 19 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/Tar/InvalidHeaderException.cs b/src/ICSharpCode.SharpZipLib/Tar/InvalidHeaderException.cs index a2e114052..9f385e425 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/InvalidHeaderException.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/InvalidHeaderException.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.Serialization; namespace ICSharpCode.SharpZipLib.Tar { @@ -6,6 +7,7 @@ namespace ICSharpCode.SharpZipLib.Tar /// This exception is used to indicate that there is a problem /// with a TAR archive header. /// + [Serializable] public class InvalidHeaderException : TarException { /// @@ -33,5 +35,21 @@ public InvalidHeaderException(string message, Exception exception) : base(message, exception) { } + + /// + /// Initializes a new instance of the InvalidHeaderException class with serialized data. + /// + /// + /// The System.Runtime.Serialization.SerializationInfo that holds the serialized + /// object data about the exception being thrown. + /// + /// + /// The System.Runtime.Serialization.StreamingContext that contains contextual information + /// about the source or destination. + /// + protected InvalidHeaderException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Serialization/SerializationTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Serialization/SerializationTests.cs index 6118022e4..cb3344ae4 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Serialization/SerializationTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Serialization/SerializationTests.cs @@ -23,6 +23,7 @@ public class SerializationTests [Category("Serialization")] [TestCase(typeof(BZip2Exception))] [TestCase(typeof(GZipException))] + [TestCase(typeof(InvalidHeaderException))] [TestCase(typeof(InvalidNameException))] [TestCase(typeof(LzwException))] [TestCase(typeof(SharpZipBaseException))] From 32920f9715bac72531cc640645d02ac8f9af50c3 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 19 Jun 2020 23:32:53 +0100 Subject: [PATCH 019/162] PR #422: Change ZipOutputStream.PutNextEntry to explicity validate the requested compression method --- src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 8f0784513..bfd308daa 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -206,6 +206,9 @@ private void WriteLeLong(long value) /// Entry name is too long
/// Finish has already been called
/// + /// + /// The Compression method specified for the entry is unsupported. + /// public void PutNextEntry(ZipEntry entry) { if (entry == null) @@ -229,6 +232,13 @@ public void PutNextEntry(ZipEntry entry) } CompressionMethod method = entry.CompressionMethod; + + // Check that the compression is one that we support + if (method != CompressionMethod.Deflated && method != CompressionMethod.Stored) + { + throw new NotImplementedException("Compression method not supported"); + } + int compressionLevel = defaultCompressionLevel; // Clear flags that the library manages internally From 7c4f517dc97dce9e6265f9f2fe0b1027da0e3215 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 4 Jul 2020 15:11:31 +0100 Subject: [PATCH 020/162] PR #479: Streamline and update VB sample projects --- .../vb/CreateZipFile/CreateZipFile.vbproj | 80 +------------------ .../vb/CreateZipFile/packages.config | 48 +---------- .../My Project/AssemblyInfo.vb | 2 +- .../WpfCreateZipFile/WpfCreateZipFile.vbproj | 80 +------------------ .../vb/WpfCreateZipFile/packages.config | 48 +---------- .../vb/minibzip2/minibzip2.vbproj | 80 +------------------ .../vb/minibzip2/packages.config | 48 +---------- .../vb/viewzipfile/packages.config | 48 +---------- .../vb/viewzipfile/viewzipfile.vbproj | 80 +------------------ .../vb/zipfiletest/packages.config | 48 +---------- .../vb/zipfiletest/zipfiletest.vbproj | 80 +------------------ 11 files changed, 16 insertions(+), 626 deletions(-) diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj index 4ed49c1cd..0188f762b 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj @@ -66,86 +66,17 @@ false - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -175,11 +106,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/My Project/AssemblyInfo.vb b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/My Project/AssemblyInfo.vb index 798a0f93a..bdef02000 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/My Project/AssemblyInfo.vb +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/My Project/AssemblyInfo.vb @@ -18,7 +18,7 @@ Imports System.Runtime.InteropServices 'NeutralResourceLanguage attribute below. Update the "en-US" in the line 'below to match the UICulture setting in the project file. - + 'The ThemeInfo attribute describes where any theme specific and generic resource dictionaries can be found. diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj index 12a8ab1d3..2bbcc5e51 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj @@ -73,90 +73,21 @@ My Project\app.manifest - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True - - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - 4.0 - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -247,11 +178,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config index 58052c86a..a01e717c5 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config @@ -1,51 +1,5 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj index d253f603c..e2a950a84 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj @@ -74,86 +74,17 @@ My Project\app.manifest - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -202,11 +133,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj index ded5b3ade..c47e0be6f 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj @@ -66,86 +66,17 @@ false - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -173,11 +104,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj index a04d2231e..ebd109ddb 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj @@ -76,86 +76,17 @@ 42353,42354,42355 - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -183,11 +114,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file From b5898dc3067c5503593b04afe82f8fea34924839 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 4 Jul 2020 17:24:25 +0100 Subject: [PATCH 021/162] PR #477: Fix spelling errors in comments --- .../Checksum/BZip2Crc.cs | 2 +- .../Core/FileSystemScanner.cs | 4 ++-- .../Lzw/LzwInputStream.cs | 2 +- src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 2 +- .../Tar/TarOutputStream.cs | 6 +++--- .../Zip/Compression/DeflaterEngine.cs | 2 +- .../Streams/InflaterInputStream.cs | 4 ++-- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 8 ++++---- .../Zip/WindowsNameTransform.cs | 2 +- .../Zip/ZipConstants.cs | 20 +++++++++---------- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 14 ++++++------- .../Zip/ZipEntryFactory.cs | 2 +- .../Zip/ZipExtraData.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 16 +++++++-------- .../Zip/ZipHelperStream.cs | 6 +++--- .../Zip/ZipInputStream.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs | 2 +- 17 files changed, 48 insertions(+), 48 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs b/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs index 9674dcec7..16cfda05b 100644 --- a/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs +++ b/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs @@ -134,7 +134,7 @@ public long Value { get { - // Tehcnically, the output should be: + // Technically, the output should be: //return (long)(~checkValue ^ crcXor); // but x ^ 0 = x, so there is no point in adding // the XOR operation diff --git a/src/ICSharpCode.SharpZipLib/Core/FileSystemScanner.cs b/src/ICSharpCode.SharpZipLib/Core/FileSystemScanner.cs index 8b01e5ff5..427e7d895 100644 --- a/src/ICSharpCode.SharpZipLib/Core/FileSystemScanner.cs +++ b/src/ICSharpCode.SharpZipLib/Core/FileSystemScanner.cs @@ -78,7 +78,7 @@ public string Name } /// - /// Get set a value indicating wether scanning should continue or not. + /// Get set a value indicating whether scanning should continue or not. /// public bool ContinueRunning { @@ -209,7 +209,7 @@ public Exception Exception } /// - /// Get / set a value indicating wether scanning should continue. + /// Get / set a value indicating whether scanning should continue. /// public bool ContinueRunning { diff --git a/src/ICSharpCode.SharpZipLib/Lzw/LzwInputStream.cs b/src/ICSharpCode.SharpZipLib/Lzw/LzwInputStream.cs index fc2a65aaa..1045ef778 100644 --- a/src/ICSharpCode.SharpZipLib/Lzw/LzwInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Lzw/LzwInputStream.cs @@ -485,7 +485,7 @@ public override void SetLength(long value) /// Writes a sequence of bytes to stream and advances the current position /// This method always throws a NotSupportedException ///
- /// Thew buffer containing data to write. + /// The buffer containing data to write. /// The offset of the first byte to write. /// The number of bytes to write. /// Any access diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs index 659334b7f..562480a3c 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs @@ -61,7 +61,7 @@ protected TarArchive() } /// - /// Initalise a TarArchive for input. + /// Initialise a TarArchive for input. /// /// The to use for input. protected TarArchive(TarInputStream stream) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs b/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs index 6efcf3a93..7c52e6c7c 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs @@ -187,7 +187,7 @@ public override int ReadByte() /// The desired number of bytes to read. /// The total number of bytes read, or zero if at the end of the stream. /// The number of bytes may be less than the count - /// requested if data is not avialable. + /// requested if data is not available. public override int Read(byte[] buffer, int offset, int count) { return outputStream.Read(buffer, offset, count); @@ -250,7 +250,7 @@ public int GetRecordSize() } /// - /// Get a value indicating wether an entry is open, requiring more data to be written. + /// Get a value indicating whether an entry is open, requiring more data to be written. /// private bool IsEntryOpen { @@ -483,7 +483,7 @@ private void WriteEofBlock() private int assemblyBufferLength; /// - /// Flag indicating wether this instance has been closed or not. + /// Flag indicating whether this instance has been closed or not. /// private bool isClosed; diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterEngine.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterEngine.cs index 2d9b5559a..556911c40 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterEngine.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterEngine.cs @@ -56,7 +56,7 @@ public class DeflaterEngine /// /// Construct instance with pending buffer - /// Adler calculation will be peformed + /// Adler calculation will be performed /// /// /// Pending buffer to use diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs index 843627d3f..bd49da036 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs @@ -596,7 +596,7 @@ public override void SetLength(long value) /// Writes a sequence of bytes to stream and advances the current position /// This method always throws a NotSupportedException /// - /// Thew buffer containing data to write. + /// The buffer containing data to write. /// The offset of the first byte to write. /// The number of bytes to write. /// Any access @@ -704,7 +704,7 @@ public override int Read(byte[] buffer, int offset, int count) protected long csize; /// - /// Flag indicating wether this instance has been closed or not. + /// Flag indicating whether this instance has been closed or not. /// private bool isClosed; diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 2e1719e88..71a739600 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -209,7 +209,7 @@ public FastZip(FastZipEvents events) #region Properties /// - /// Get/set a value indicating wether empty directories should be created. + /// Get/set a value indicating whether empty directories should be created. /// public bool CreateEmptyDirectories { @@ -267,7 +267,7 @@ public IEntryFactory EntryFactory /// read Zip64 archives. However it does avoid the situation were a large file /// is added and cannot be completed correctly. /// NOTE: Setting the size for entries before they are added is the best solution! - /// By default the EntryFactory used by FastZip will set fhe file size. + /// By default the EntryFactory used by FastZip will set the file size. /// public UseZip64 UseZip64 { @@ -276,7 +276,7 @@ public UseZip64 UseZip64 } /// - /// Get/set a value indicating wether file dates and times should + /// Get/set a value indicating whether file dates and times should /// be restored when extracting files from an archive. /// /// The default value is false. @@ -533,7 +533,7 @@ private void ProcessFile(object sender, ScanEventArgs e) { try { - // The open below is equivalent to OpenRead which gaurantees that if opened the + // The open below is equivalent to OpenRead which guarantees that if opened the // file will not be changed by subsequent openers, but precludes opening in some cases // were it could succeed. ie the open may fail as its already open for writing and the share mode should reflect that. using (FileStream stream = File.Open(e.Name, FileMode.Open, FileAccess.Read, FileShare.Read)) diff --git a/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs b/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs index 75d97ff19..c10f5ceab 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs @@ -81,7 +81,7 @@ public bool AllowParentTraversal } /// - /// Gets or sets a value indicating wether paths on incoming values should be removed. + /// Gets or sets a value indicating whether paths on incoming values should be removed. /// public bool TrimIncomingPaths { diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs index 9e0a8764a..cc2fd27d2 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs @@ -161,7 +161,7 @@ public enum GeneralBitFlags Method = 0x0006, /// - /// Bit 3 if set indicates a trailing data desciptor is appended to the entry data + /// Bit 3 if set indicates a trailing data descriptor is appended to the entry data /// Descriptor = 0x0008, @@ -443,12 +443,12 @@ public static class ZipConstants public const int ArchiveExtraDataSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24); /// - /// Central header digitial signature + /// Central header digital signature /// public const int CentralHeaderDigitalSignature = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); /// - /// Central header digitial signature + /// Central header digital signature /// [Obsolete("Use CentralHeaderDigitalSignaure instead")] public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); @@ -468,7 +468,7 @@ public static class ZipConstants /// /// Default encoding used for string conversion. 0 gives the default system OEM code page. - /// Using the default code page isnt the full solution neccessarily + /// Using the default code page isnt the full solution necessarily /// there are many variable factors, codepage 850 is often a good choice for /// European users, however be careful about compatability. /// @@ -479,32 +479,32 @@ public static int DefaultCodePage set => ZipStrings.CodePage = value; } - /// Depracated wrapper for + /// Deprecated wrapper for [Obsolete("Use ZipStrings.ConvertToString instead")] public static string ConvertToString(byte[] data, int count) => ZipStrings.ConvertToString(data, count); - /// Depracated wrapper for + /// Deprecated wrapper for [Obsolete("Use ZipStrings.ConvertToString instead")] public static string ConvertToString(byte[] data) => ZipStrings.ConvertToString(data); - /// Depracated wrapper for + /// Deprecated wrapper for [Obsolete("Use ZipStrings.ConvertToStringExt instead")] public static string ConvertToStringExt(int flags, byte[] data, int count) => ZipStrings.ConvertToStringExt(flags, data, count); - /// Depracated wrapper for + /// Deprecated wrapper for [Obsolete("Use ZipStrings.ConvertToStringExt instead")] public static string ConvertToStringExt(int flags, byte[] data) => ZipStrings.ConvertToStringExt(flags, data); - /// Depracated wrapper for + /// Deprecated wrapper for [Obsolete("Use ZipStrings.ConvertToArray instead")] public static byte[] ConvertToArray(string str) => ZipStrings.ConvertToArray(str); - /// Depracated wrapper for + /// Deprecated wrapper for [Obsolete("Use ZipStrings.ConvertToArray instead")] public static byte[] ConvertToArray(int flags, string str) => ZipStrings.ConvertToArray(flags, str); diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index a6241cb0f..7d15b01d2 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -261,7 +261,7 @@ public ZipEntry(ZipEntry entry) #endregion Constructors /// - /// Get a value indicating wether the entry has a CRC value available. + /// Get a value indicating whether the entry has a CRC value available. /// public bool HasCrc { @@ -296,7 +296,7 @@ public bool IsCrypted } /// - /// Get / set a flag indicating wether entry name and comment text are + /// Get / set a flag indicating whether entry name and comment text are /// encoded in unicode UTF8. /// /// This is an assistant that interprets the flags property. @@ -606,7 +606,7 @@ public int Version /// Get a value indicating whether this entry can be decompressed by the library. /// /// This is based on the and - /// wether the compression method is supported. + /// whether the compression method is supported. public bool CanDecompress { get @@ -630,7 +630,7 @@ public void ForceZip64() } /// - /// Get a value indicating wether Zip64 extensions were forced. + /// Get a value indicating whether Zip64 extensions were forced. /// /// A value of true if Zip64 extensions have been forced on; false if not. public bool IsZip64Forced() @@ -670,7 +670,7 @@ public bool LocalHeaderRequiresZip64 } /// - /// Get a value indicating wether the central directory entry requires Zip64 extensions to be stored. + /// Get a value indicating whether the central directory entry requires Zip64 extensions to be stored. /// public bool CentralHeaderRequiresZip64 { @@ -901,7 +901,7 @@ public byte[] ExtraData { get { - // TODO: This is slightly safer but less efficient. Think about wether it should change. + // TODO: This is slightly safer but less efficient. Think about whether it should change. // return (byte[]) extra.Clone(); return extra; } @@ -1059,7 +1059,7 @@ internal void ProcessExtraData(bool localHeader) // flag 13 is set indicating masking, the value stored for the // uncompressed size in the Local Header will be zero. // - // Othewise there is problem with minizip implementation + // Otherwise there is problem with minizip implementation if (size == uint.MaxValue) { size = (ulong)extraData.ReadLong(); diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs index d5750f0a6..e82eafc48 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs @@ -162,7 +162,7 @@ public int SetAttributes } /// - /// Get set a value indicating wether unidoce text should be set on. + /// Get set a value indicating whether unidoce text should be set on. /// public bool IsUnicodeText { diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs index 9e0e8037f..0535b1250 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs @@ -3,7 +3,7 @@ namespace ICSharpCode.SharpZipLib.Zip { - // TODO: Sort out wether tagged data is useful and what a good implementation might look like. + // TODO: Sort out whether tagged data is useful and what a good implementation might look like. // Its just a sketch of an idea at the moment. /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 59ba3f950..a408206c2 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -191,7 +191,7 @@ public long BytesTested } /// - /// Get a value indicating wether the last entry test was valid. + /// Get a value indicating whether the last entry test was valid. /// public bool EntryValid { @@ -318,7 +318,7 @@ public class ZipFile : IEnumerable, IDisposable #region KeyHandling /// - /// Delegate for handling keys/password setting during compresion/decompression. + /// Delegate for handling keys/password setting during compression/decompression. /// public delegate void KeysRequiredEventHandler( object sender, @@ -375,7 +375,7 @@ public string Password } /// - /// Get a value indicating wether encryption keys are currently available. + /// Get a value indicating whether encryption keys are currently available. /// private bool HaveKeys { @@ -654,7 +654,7 @@ public bool IsStreamOwner } /// - /// Get a value indicating wether + /// Get a value indicating whether /// this archive is embedded in another file or not. /// public bool IsEmbeddedArchive @@ -2094,7 +2094,7 @@ private void WriteLocalEntryHeader(ZipUpdate update) break; case UseZip64.Off: - // Do nothing. The entry itself may be using Zip64 independantly. + // Do nothing. The entry itself may be using Zip64 independently. break; } } @@ -3395,7 +3395,7 @@ private void ReadEntries() // // The search is limited to 64K which is the maximum size of a trailing comment field to aid speed. // This should be compatible with both SFX and ZIP files but has only been tested for Zip files - // If a SFX file has the Zip data attached as a resource and there are other resources occuring later then + // If a SFX file has the Zip data attached as a resource and there are other resources occurring later then // this could be invalid. // Could also speed this up by reading memory in larger blocks. @@ -4381,7 +4381,7 @@ public interface IDynamicDataSource public class StaticDiskDataSource : IStaticDataSource { /// - /// Initialise a new instnace of + /// Initialise a new instance of /// /// The name of the file to obtain data from. public StaticDiskDataSource(string fileName) @@ -4394,7 +4394,7 @@ public StaticDiskDataSource(string fileName) /// /// Get a providing data. /// - /// Returns a provising data. + /// Returns a providing data. public Stream GetSource() { return File.Open(fileName_, FileMode.Open, FileAccess.Read, FileShare.Read); diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs index 03567b3bf..b66716014 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs @@ -95,7 +95,7 @@ public ZipHelperStream(Stream stream) #endregion Constructors /// - /// Get / set a value indicating wether the the underlying stream is owned or not. + /// Get / set a value indicating whether the the underlying stream is owned or not. /// /// If the stream is owned it is closed when this instance is closed. public bool IsStreamOwner @@ -303,7 +303,7 @@ private void WriteLocalHeader(ZipEntry entry, EntryPatchData patchData) /// Location, marking the end of block. /// Minimum size of the block. /// The maximum variable data. - /// Eeturns the offset of the first byte after the signature; -1 if not found + /// Returns the offset of the first byte after the signature; -1 if not found public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) { long pos = endLocation - minimumBlockSize; @@ -332,7 +332,7 @@ public long LocateBlockWithSignature(int signature, long endLocation, int minimu /// /// The number of entries in the central directory. /// The size of entries in the central directory. - /// The offset of the dentral directory. + /// The offset of the central directory. public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset) { long centralSignatureOffset = centralDirOffset + sizeEntries; diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs index b9c8d8c35..147d4043d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs @@ -585,7 +585,7 @@ public override int Read(byte[] buffer, int offset, int count) /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. /// /// - /// An i/o error occured. + /// An i/o error occurred. /// /// /// The deflated stream is corrupted. diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs index eff29a3ce..6ef523b82 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs @@ -66,7 +66,7 @@ public static int CodePage public static int SystemDefaultCodePage { get; } /// - /// Get wether the default codepage is set to UTF-8. Setting this property to false will + /// Get whether the default codepage is set to UTF-8. Setting this property to false will /// set the to /// /// From b6ab9f5da988dbcc87b54def87e7340c19358844 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 4 Jul 2020 17:29:04 +0100 Subject: [PATCH 022/162] PR #476: Remove duplicated words in comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: nils måsén --- .../Core/Exceptions/ValueOutOfRangeException.cs | 6 +++--- src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs | 4 ++-- src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs | 2 +- .../Zip/Compression/Streams/InflaterInputStream.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Core/Exceptions/ValueOutOfRangeException.cs b/src/ICSharpCode.SharpZipLib/Core/Exceptions/ValueOutOfRangeException.cs index aefefb61e..d41cf9882 100644 --- a/src/ICSharpCode.SharpZipLib/Core/Exceptions/ValueOutOfRangeException.cs +++ b/src/ICSharpCode.SharpZipLib/Core/Exceptions/ValueOutOfRangeException.cs @@ -10,14 +10,14 @@ namespace ICSharpCode.SharpZipLib public class ValueOutOfRangeException : StreamDecodingException { /// - /// Initializes a new instance of the ValueOutOfRangeException class naming the the causing variable + /// Initializes a new instance of the ValueOutOfRangeException class naming the causing variable /// /// Name of the variable, use: nameof() public ValueOutOfRangeException(string nameOfValue) : base($"{nameOfValue} out of range") { } /// - /// Initializes a new instance of the ValueOutOfRangeException class naming the the causing variable, + /// Initializes a new instance of the ValueOutOfRangeException class naming the causing variable, /// it's current value and expected range. /// /// Name of the variable, use: nameof() @@ -28,7 +28,7 @@ public ValueOutOfRangeException(string nameOfValue, long value, long maxValue, l : this(nameOfValue, value.ToString(), maxValue.ToString(), minValue.ToString()) { } /// - /// Initializes a new instance of the ValueOutOfRangeException class naming the the causing variable, + /// Initializes a new instance of the ValueOutOfRangeException class naming the causing variable, /// it's current value and expected range. /// /// Name of the variable, use: nameof() diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs b/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs index 43a6d5cdf..744c13189 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs @@ -345,7 +345,7 @@ private bool ReadRecord() { if (inputStream == null) { - throw new TarException("no input stream stream defined"); + throw new TarException("no input stream defined"); } currentBlockIndex = 0; @@ -492,7 +492,7 @@ public void WriteBlock(byte[] buffer, int offset) if (outputStream == null) { - throw new TarException("TarBuffer.WriteBlock - no output stream stream defined"); + throw new TarException("TarBuffer.WriteBlock - no output stream defined"); } if ((offset < 0) || (offset >= buffer.Length)) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs b/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs index 078ff0a0f..f1a3622de 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs @@ -662,7 +662,7 @@ public interface IEntryFactory /// Create a tar entry based on the header information passed /// /// - /// Buffer containing header information to create an an entry from. + /// Buffer containing header information to create an entry from. /// /// /// Created TarEntry or descendant class diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs index bd49da036..3fb257906 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs @@ -42,7 +42,7 @@ public InflaterInputBuffer(Stream stream, int bufferSize) #endregion Constructors /// - /// Get the length of bytes bytes in the + /// Get the length of bytes in the /// public int RawLength { diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index a408206c2..c12a53df1 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -130,7 +130,7 @@ public enum TestOperation } /// - /// Status returned returned by during testing. + /// Status returned by during testing. /// /// TestArchive public class TestStatus diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs index b66716014..dd7d25d94 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs @@ -95,7 +95,7 @@ public ZipHelperStream(Stream stream) #endregion Constructors /// - /// Get / set a value indicating whether the the underlying stream is owned or not. + /// Get / set a value indicating whether the underlying stream is owned or not. /// /// If the stream is owned it is closed when this instance is closed. public bool IsStreamOwner From 1e8fdfa726420e6a3b13099bb0f24c14b94bbf2b Mon Sep 17 00:00:00 2001 From: Christoph Wille Date: Mon, 3 Aug 2020 19:10:46 +0200 Subject: [PATCH 023/162] SharpZipLib is now using GH Discussions and no longer gitter.im --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9a06f1ca8..2ff6e2c32 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# SharpZipLib [![Build status](https://ci.appveyor.com/api/projects/status/wuf8l79mypqsbor3/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/sharpziplib/branch/master) [![Join the chat at https://gitter.im/icsharpcode/SharpZipLib](https://badges.gitter.im/icsharpcode/SharpZipLib.svg)](https://gitter.im/icsharpcode/SharpZipLib?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) +# SharpZipLib [![Build status](https://ci.appveyor.com/api/projects/status/wuf8l79mypqsbor3/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/sharpziplib/branch/master) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) The SharpZipLib project is looking for a new maintainer - please read [State of the Union August 2017](https://github.com/icsharpcode/SharpZipLib/issues/187) From a11665d4a190839f56e74ae0df2393346e3608cc Mon Sep 17 00:00:00 2001 From: Christoph Wille Date: Mon, 3 Aug 2020 19:11:05 +0200 Subject: [PATCH 024/162] Remove state of the union from 2017 --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 2ff6e2c32..269cb048b 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@ # SharpZipLib [![Build status](https://ci.appveyor.com/api/projects/status/wuf8l79mypqsbor3/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/sharpziplib/branch/master) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) -The SharpZipLib project is looking for a new maintainer - please read [State of the Union August 2017](https://github.com/icsharpcode/SharpZipLib/issues/187) - Introduction ------------ From 2082f944a390dd5aec0130251c3f7845515a3760 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Thu, 6 Aug 2020 16:50:49 +0100 Subject: [PATCH 025/162] PR #498: Use string.Trim to trim strings (#498) --- src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs index 1b5e01a68..b0c8b72cb 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs @@ -95,17 +95,8 @@ public string TransformFile(string name) name = name.Replace(@"\", "/"); name = WindowsPathUtils.DropPathRoot(name); - // Drop any leading slashes. - while ((name.Length > 0) && (name[0] == '/')) - { - name = name.Remove(0, 1); - } - - // Drop any trailing slashes. - while ((name.Length > 0) && (name[name.Length - 1] == '/')) - { - name = name.Remove(name.Length - 1, 1); - } + // Drop any leading and trailing slashes. + name = name.Trim('/'); // Convert consecutive // characters to / int index = name.IndexOf("//", StringComparison.Ordinal); From 70e20007f97a56952a167daa6d059209fc971f2e Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 7 Aug 2020 14:23:52 +0100 Subject: [PATCH 026/162] PR #494: Use the Range to test different compression levels in InflaterDeflaterTestSuite --- .../Base/InflaterDeflaterTests.cs | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs index 1d736558e..cf7b72456 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs @@ -104,12 +104,9 @@ private void RandomDeflateInflate(int size, int level, bool zlib) /// [Test] [Category("Base")] - public void InflateDeflateZlib() + public void InflateDeflateZlib([Range(0, 9)] int level) { - for (int level = 0; level < 10; ++level) - { - RandomDeflateInflate(100000, level, true); - } + RandomDeflateInflate(100000, level, true); } private delegate void RunCompress(byte[] buffer); @@ -167,14 +164,12 @@ private void TryManyVariants(int level, bool zlib, RunCompress test, byte[] buff /// [Test] [Category("Base")] - public void InflateDeflateNonZlib() + public void InflateDeflateNonZlib([Range(0, 9)] int level) { - for (int level = 0; level < 10; ++level) - { - RandomDeflateInflate(100000, level, false); - } + RandomDeflateInflate(100000, level, false); } + [Test] [Category("Base")] public void CloseDeflatorWithNestedUsing() From b07ecb40b027e926723c82e7528f47b1fad0de58 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 7 Aug 2020 14:34:17 +0100 Subject: [PATCH 027/162] PR #489: Remove duplicate ICSharpCode.SharpZipLib.snk --- .../ICSharpCode.SharpZipLib.snk | Bin .../ICSharpCode.SharpZipLib.csproj | 2 +- .../ICSharpCode.SharpZipLib.snk | Bin 596 -> 0 bytes 3 files changed, 1 insertion(+), 1 deletion(-) rename {src/ICSharpCode.SharpZipLib => assets}/ICSharpCode.SharpZipLib.snk (100%) delete mode 100644 test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.snk diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.snk b/assets/ICSharpCode.SharpZipLib.snk similarity index 100% rename from src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.snk rename to assets/ICSharpCode.SharpZipLib.snk diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index ea7bdf756..3d0654f32 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -3,7 +3,7 @@ netstandard2;net45 True - ICSharpCode.SharpZipLib.snk + ../../assets/ICSharpCode.SharpZipLib.snk true true $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb diff --git a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.snk b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.snk deleted file mode 100644 index 58cf194dfdb9ac183edd43614d60de5ada399419..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 596 zcmV-a0;~N80ssI2Bme+XQ$aES1ONa50098Gp-!m$opqVu=qeJDqA>&TAr3E+iVsF< zW3MCs`rDwr3N0M^KYF`#hqG3CPXtz~W@i;lXGyX1 zb?B}~=4AN^h_0Cpj+XbMoWaMn6QSKJrHllU7x*~1X~gvus8fe?!3>7i;&QznoP}U{ zz^^d~3jkzuMI!8@SU|_Ab$YY^?njPb#^@kt!}Cm5^kjS3{;DH`qQTUteSbDE`6xZ9 zG>cf2D#ne>782Mna@FZR&$2j-wll!(ga_d4_l&g~!2LEuu-NtFY*>nvqe7^RANsYV zzC+Y9a(P$Ol14we*lUP&>c`sM0pr3FRH zmQbg6*TC~B$I9s$X(&$X&Unt?2)3_%Jw83A{8o2)qPFEh4ri9t5>pj%G<7$0QO8L1 zwF_voriSbH=M5Bbyexi4;n^;N+CCcWHI^Ul%`sRTmbaJ?1mcW}oXciF_XpKaEjmZF z`5gsxG;W8%RN|N5qnZ>Zo!4ok^Yb{WM;>)n Date: Fri, 7 Aug 2020 14:35:52 +0100 Subject: [PATCH 028/162] #488: Add [MemoryDiagnoser] to the zip input/output stream benchmark classes --- .../ICSharpCode.SharpZipLib.Benchmark/Zip/ZipInputStream.cs | 5 +++-- .../ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipInputStream.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipInputStream.cs index d112e22e3..eb099ebfd 100644 --- a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipInputStream.cs +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipInputStream.cs @@ -4,6 +4,7 @@ namespace ICSharpCode.SharpZipLib.Benchmark.Zip { + [MemoryDiagnoser] [Config(typeof(MultipleRuntimes))] public class ZipInputStream { @@ -12,6 +13,7 @@ public class ZipInputStream private const int N = ChunkCount * ChunkSize; byte[] zippedData; + byte[] readBuffer = new byte[4096]; public ZipInputStream() { @@ -40,10 +42,9 @@ public long ReadZipInputStream() { using (var zipInputStream = new SharpZipLib.Zip.ZipInputStream(memoryStream)) { - var buffer = new byte[4096]; var entry = zipInputStream.GetNextEntry(); - while (zipInputStream.Read(buffer, 0, buffer.Length) > 0) + while (zipInputStream.Read(readBuffer, 0, readBuffer.Length) > 0) { } diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs index 0f7b5c7c4..0727ea6f2 100644 --- a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs @@ -4,6 +4,7 @@ namespace ICSharpCode.SharpZipLib.Benchmark.Zip { + [MemoryDiagnoser] [Config(typeof(MultipleRuntimes))] public class ZipOutputStream { From 75adef54559ee77c6e36dd4702c84d623ef0c540 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 7 Aug 2020 14:37:52 +0100 Subject: [PATCH 029/162] PR #455: Add FastZip.CreateZip with a leaveOpen parameter * Add a variant of FastZip.CreateZip with a leaveOpen parameter to control output stream disposal * Add unit test for FastZip.CreateZip leaving the stream open or disposed as required --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 15 +++++++ .../Zip/FastZipHandling.cs | 40 +++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 71a739600..16da8b455 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -361,6 +361,20 @@ public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, /// The directory filter to apply. /// The is closed after creation. public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) + { + CreateZip(outputStream, sourceDirectory, recurse, fileFilter, directoryFilter, false); + } + + /// + /// Create a zip archive sending output to the passed. + /// + /// The stream to write archive data to. + /// The directory to source files from. + /// True to recurse directories, false for no recursion. + /// The file filter to apply. + /// The directory filter to apply. + /// true to leave open after the zip has been created, false to dispose it. + public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter, bool leaveOpen) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; @@ -368,6 +382,7 @@ public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, using (outputStream_ = new ZipOutputStream(outputStream)) { outputStream_.SetLevel((int)CompressionLevel); + outputStream_.IsStreamOwner = !leaveOpen; if (password_ != null) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 67b481f65..259bde43b 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -625,5 +625,45 @@ public void SetDirectoryModifiedDate() Directory.Delete(targetDir, true); } } + + /// + /// Test for https://github.com/icsharpcode/SharpZipLib/issues/78 + /// + /// if true, the stream given to CreateZip should be left open, if false it should be disposed. + [TestCase(true)] + [TestCase(false)] + [Category("Zip")] + [Category("CreatesTempFile")] + public void CreateZipShouldLeaveOutputStreamOpenIfRequested(bool leaveOpen) + { + const string tempFileName = "a(2).dat"; + + using (var tempFolder = new Utils.TempDir()) + { + // Create test input file + string addFile = Path.Combine(tempFolder.Fullpath, tempFileName); + MakeTempFile(addFile, 16); + + // Create the zip with fast zip + var target = new TrackedMemoryStream(); + var fastZip = new FastZip(); + + fastZip.CreateZip(target, tempFolder.Fullpath, false, @"a\(2\)\.dat", null, leaveOpen: leaveOpen); + + // Check that the output stream was disposed (or not) as expected + Assert.That(target.IsDisposed, Is.Not.EqualTo(leaveOpen), "IsDisposed should be the opposite of leaveOpen"); + + // Check that the file contents are correct in both cases + var archive = new MemoryStream(target.ToArray()); + using (ZipFile zf = new ZipFile(archive)) + { + Assert.AreEqual(1, zf.Count); + ZipEntry entry = zf[0]; + Assert.AreEqual(tempFileName, entry.Name); + Assert.AreEqual(16, entry.Size); + Assert.IsTrue(zf.TestArchive(true)); + } + } + } } } From f593921a3990e5f38f7937641a5c0306782ef6dd Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 7 Aug 2020 14:49:23 +0100 Subject: [PATCH 030/162] PR #458: Dispose of entry streams returned by ZipFile.GetInputStream --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 16da8b455..aba4ffaea 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -636,14 +636,18 @@ private void ExtractFileEntry(ZipEntry entry, string targetName) { buffer_ = new byte[4096]; } - if ((events_ != null) && (events_.Progress != null)) - { - StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_, - events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size); - } - else + + using (var inputStream = zipFile_.GetInputStream(entry)) { - StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_); + if ((events_ != null) && (events_.Progress != null)) + { + StreamUtils.Copy(inputStream, outputStream, buffer_, + events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size); + } + else + { + StreamUtils.Copy(inputStream, outputStream, buffer_); + } } if (events_ != null) From 3835f0c0c9b3b715e0aec1df09871392b593ced6 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 7 Aug 2020 14:53:06 +0100 Subject: [PATCH 031/162] PR #483: Suppress CA1707 warnings from LzwConstants --- src/ICSharpCode.SharpZipLib/Lzw/LzwConstants.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ICSharpCode.SharpZipLib/Lzw/LzwConstants.cs b/src/ICSharpCode.SharpZipLib/Lzw/LzwConstants.cs index b7dc60f59..88934830f 100644 --- a/src/ICSharpCode.SharpZipLib/Lzw/LzwConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Lzw/LzwConstants.cs @@ -3,6 +3,7 @@ namespace ICSharpCode.SharpZipLib.Lzw /// /// This class contains constants used for LZW /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "kept for backwards compatibility")] sealed public class LzwConstants { /// From bf4372aec20a1540487d7e0a67b0cae9b0713a0b Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Fri, 7 Aug 2020 15:41:24 +0100 Subject: [PATCH 032/162] PR #460: Account for AES overhead in compressed entry size (#460) * Unit test for writing encrypted 0 byte files to ZipOutputStream * In ZipOutputStream.PutNextEntry, account for AES overhead when calculating compressed entry size --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 22 +++++++++++- .../Zip/ZipOutputStream.cs | 13 ++----- .../Zip/ZipEncryptionHandling.cs | 36 +++++++++++++++++++ 3 files changed, 60 insertions(+), 11 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index 7d15b01d2..14f760286 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -655,7 +655,7 @@ public bool LocalHeaderRequiresZip64 if ((versionToExtract == 0) && IsCrypted) { - trueCompressedSize += ZipConstants.CryptoHeaderSize; + trueCompressedSize += (ulong)this.EncryptionOverheadSize; } // TODO: A better estimation of the true limit based on compression overhead should be used @@ -1013,6 +1013,26 @@ internal int AESOverheadSize } } + /// + /// Number of extra bytes required to hold the encryption header fields. + /// + internal int EncryptionOverheadSize + { + get + { + // Entry is not encrypted - no overhead + if (!this.IsCrypted) + return 0; + + // Entry is encrypted using ZipCrypto + if (_aesEncryptionStrength == 0) + return ZipConstants.CryptoHeaderSize; + + // Entry is encrypted using AES + return this.AESOverheadSize; + } + } + /// /// Process extra data fields updating the entry based on the contents. /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index bfd308daa..fe5079e07 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -337,7 +337,7 @@ public void PutNextEntry(ZipEntry entry) } else { - WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); + WriteLeInt((int)entry.CompressedSize + entry.EncryptionOverheadSize); WriteLeInt((int)entry.Size); } } @@ -382,7 +382,7 @@ public void PutNextEntry(ZipEntry entry) if (headerInfoAvailable) { ed.AddLeLong(entry.Size); - ed.AddLeLong(entry.CompressedSize); + ed.AddLeLong(entry.CompressedSize + entry.EncryptionOverheadSize); } else { @@ -540,14 +540,7 @@ public void CloseEntry() if (curEntry.IsCrypted) { - if (curEntry.AESKeySize > 0) - { - curEntry.CompressedSize += curEntry.AESOverheadSize; - } - else - { - curEntry.CompressedSize += ZipConstants.CryptoHeaderSize; - } + curEntry.CompressedSize += curEntry.EncryptionOverheadSize; } // Patch the header if possible diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index f9c988df1..d77e309b0 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -42,6 +42,42 @@ public void ZipCryptoEncryption(CompressionMethod compressionMethod) CreateZipWithEncryptedEntries("foo", 0, compressionMethod); } + /// + /// Test Known zero length encrypted entries with ZipOutputStream. + /// These are entries where the entry size is set to 0 ahead of time, so that PutNextEntry will fill in the header and there will be no patching. + /// Test with Zip64 on and off, as the logic is different for the two. + /// + [Test] + public void ZipOutputStreamEncryptEmptyEntries( + [Values] UseZip64 useZip64, + [Values(0, 128, 256)] int keySize, + [Values(CompressionMethod.Stored, CompressionMethod.Deflated)] CompressionMethod compressionMethod) + { + using (var ms = new MemoryStream()) + { + using (var zipOutputStream = new ZipOutputStream(ms)) + { + zipOutputStream.IsStreamOwner = false; + zipOutputStream.Password = "password"; + zipOutputStream.UseZip64 = useZip64; + + ZipEntry zipEntry = new ZipEntry("emptyEntry") + { + AESKeySize = keySize, + CompressionMethod = compressionMethod, + CompressedSize = 0, + Crc = 0, + Size = 0, + }; + + zipOutputStream.PutNextEntry(zipEntry); + zipOutputStream.CloseEntry(); + } + + VerifyZipWith7Zip(ms, "password"); + } + } + [Test] [Category("Encryption")] [Category("Zip")] From 24f948af9289d004c925848a466db1450d26f7d6 Mon Sep 17 00:00:00 2001 From: Vladyslav Taranov Date: Fri, 7 Aug 2020 17:52:00 +0300 Subject: [PATCH 033/162] PR #402 Only convert entry.Name once when accessing updateIndex MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * don't convert entry.Name twice when accessing updateIndex * Update src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs Accepted suggestion Co-Authored-By: nils måsén * Update src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs Co-Authored-By: nils måsén * Update src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs Co-Authored-By: nils måsén * Update src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs Co-Authored-By: nils måsén Co-authored-by: nils måsén --- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index c12a53df1..056785e16 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1626,7 +1626,7 @@ private void AddUpdate(ZipUpdate update) { contentsEdited_ = true; - int index = FindExistingUpdate(update.Entry.Name); + int index = FindExistingUpdate(update.Entry.Name, isEntryName: true); if (index >= 0) { @@ -2555,13 +2555,9 @@ private void CopyEntryDataDirect(ZipUpdate update, Stream stream, bool updateCrc private int FindExistingUpdate(ZipEntry entry) { int result = -1; - string convertedName = entry.IsDirectory - ? GetTransformedDirectoryName(entry.Name) - : GetTransformedFileName(entry.Name); - - if (updateIndex_.ContainsKey(convertedName)) + if (updateIndex_.ContainsKey(entry.Name)) { - result = (int)updateIndex_[convertedName]; + result = (int)updateIndex_[entry.Name]; } /* // This is slow like the coming of the next ice age but takes less storage and may be useful @@ -2579,11 +2575,11 @@ private int FindExistingUpdate(ZipEntry entry) return result; } - private int FindExistingUpdate(string fileName) + private int FindExistingUpdate(string fileName, bool isEntryName = false) { int result = -1; - string convertedName = GetTransformedFileName(fileName); + string convertedName = !isEntryName ? GetTransformedFileName(fileName) : fileName; if (updateIndex_.ContainsKey(convertedName)) { From 71cc7bbd0f081079cb101185cfdf7defb3f9d1c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 8 Aug 2020 17:01:53 +0200 Subject: [PATCH 034/162] PR #502: Fix tests and ZipEntry DateTime Kind * Normalize DateTime kind in ZipEntry * Use Unspecifed DateTime Kind for entries * Fix tests --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 2 +- .../Zip/StreamHandling.cs | 35 +++++++++++++++++-- .../Zip/WindowsNameTransformHandling.cs | 8 +++++ .../Zip/ZipEntryFactoryHandling.cs | 1 + .../Zip/ZipNameTransformHandling.cs | 14 +++++--- 5 files changed, 53 insertions(+), 7 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index 14f760286..f119a1c4a 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -742,7 +742,7 @@ public long DosTime uint mon = Math.Max(1, Math.Min(12, ((uint)(value >> 21) & 0xf))); uint year = ((dosTime >> 25) & 0x7f) + 1980; int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((value >> 16) & 0x1f))); - DateTime = new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Utc); + DateTime = new DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec, DateTimeKind.Unspecified); } } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index 5ba337f51..1adebe2ab 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -244,11 +244,14 @@ public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLengt using (var dummyZip = Utils.GetDummyFile(0)) using (var inputFile = Utils.GetDummyFile(contentLength)) { + // Filename is manually cleaned here to prevent this test from failing while ZipEntry doesn't automatically clean it + var inputFileName = ZipEntry.CleanName(inputFile.Filename); + using (var zipFileStream = File.OpenWrite(dummyZip.Filename)) using (var zipOutputStream = new ZipOutputStream(zipFileStream)) using (var inputFileStream = File.OpenRead(inputFile.Filename)) { - zipOutputStream.PutNextEntry(new ZipEntry(inputFile.Filename) + zipOutputStream.PutNextEntry(new ZipEntry(inputFileName) { CompressionMethod = CompressionMethod.Stored, }); @@ -260,7 +263,6 @@ public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLengt { var inputBytes = File.ReadAllBytes(inputFile.Filename); - var inputFileName = ZipEntry.CleanName(inputFile.Filename); var entry = zf.GetEntry(inputFileName); Assert.IsNotNull(entry, "No entry matching source file \"{0}\" found in archive, found \"{1}\"", inputFileName, zf[0].Name); @@ -282,6 +284,35 @@ public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLengt } } + [Test] + [Category("Zip")] + [Category("KnownBugs")] + public void ZipEntryFileNameAutoClean() + { + using (var dummyZip = Utils.GetDummyFile(0)) + using (var inputFile = Utils.GetDummyFile()) { + using (var zipFileStream = File.OpenWrite(dummyZip.Filename)) + using (var zipOutputStream = new ZipOutputStream(zipFileStream)) + using (var inputFileStream = File.OpenRead(inputFile.Filename)) + { + zipOutputStream.PutNextEntry(new ZipEntry(inputFile.Filename) + { + CompressionMethod = CompressionMethod.Stored, + }); + + inputFileStream.CopyTo(zipOutputStream); + } + + using (var zf = new ZipFile(dummyZip.Filename)) + { + Assert.AreNotEqual(ZipEntry.CleanName(inputFile.Filename), zf[0].Name, + "Entry file name \"{0}\" WAS automatically cleaned, this test should be removed", inputFile.Filename); + } + + Assert.Warn("Entry file name \"{0}\" was not automatically cleaned", inputFile.Filename); + } + } + /// /// Empty zips can be created and read? /// diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/WindowsNameTransformHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/WindowsNameTransformHandling.cs index 7e7d440be..8e6941251 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/WindowsNameTransformHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/WindowsNameTransformHandling.cs @@ -2,12 +2,20 @@ using NUnit.Framework; using System; using System.IO; +using System.Runtime.InteropServices; namespace ICSharpCode.SharpZipLib.Tests.Zip { [TestFixture] public class WindowsNameTransformHandling : TransformBase { + [OneTimeSetUp] + public void TestInit() { + if (Path.DirectorySeparatorChar != '\\') { + Assert.Inconclusive("WindowsNameTransform will not work on platforms not using '\\' directory separators"); + } + } + [Test] public void BasicFiles() { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs index ab2ae3744..c1ba17f64 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs @@ -106,6 +106,7 @@ public void CreatedValues() var lastAccessTime = new DateTime(2050, 11, 3, 0, 42, 12); string tempFile = Path.Combine(tempDir, "SharpZipTest.Zip"); + using (FileStream f = File.Create(tempFile, 1024)) { f.WriteByte(0); diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs index 634b9a0ab..498a8f723 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs @@ -80,10 +80,16 @@ public void NameTransforms() [Category("Zip")] public void FilenameCleaning() { - Assert.AreEqual(0, string.Compare(ZipEntry.CleanName("hello"), "hello", StringComparison.Ordinal)); - Assert.AreEqual(0, string.Compare(ZipEntry.CleanName(@"z:\eccles"), "eccles", StringComparison.Ordinal)); - Assert.AreEqual(0, string.Compare(ZipEntry.CleanName(@"\\server\share\eccles"), "eccles", StringComparison.Ordinal)); - Assert.AreEqual(0, string.Compare(ZipEntry.CleanName(@"\\server\share\dir\eccles"), "dir/eccles", StringComparison.Ordinal)); + Assert.AreEqual(ZipEntry.CleanName("hello"), "hello"); + if(Environment.OSVersion.Platform == PlatformID.Win32NT) + { + Assert.AreEqual(ZipEntry.CleanName(@"z:\eccles"), "eccles"); + Assert.AreEqual(ZipEntry.CleanName(@"\\server\share\eccles"), "eccles"); + Assert.AreEqual(ZipEntry.CleanName(@"\\server\share\dir\eccles"), "dir/eccles"); + } + else { + Assert.AreEqual(ZipEntry.CleanName(@"/eccles"), "eccles"); + } } [Test] From 3491abb6aa0fec56bd98d8e5ac7a6ae795c1a59f Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 9 Aug 2020 16:55:12 +0100 Subject: [PATCH 035/162] PR #482: Add variants of FastZip.CreateZip taking IScanFilter instead of strings --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 44 ++++++++++++++++++- .../Zip/FastZipHandling.cs | 2 +- 2 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index aba4ffaea..6c7e106e2 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -375,6 +375,49 @@ public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, /// The directory filter to apply. /// true to leave open after the zip has been created, false to dispose it. public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter, bool leaveOpen) + { + var scanner = new FileSystemScanner(fileFilter, directoryFilter); + CreateZip(outputStream, sourceDirectory, recurse, scanner, leaveOpen); + } + + /// + /// Create a zip file. + /// + /// The name of the zip file to create. + /// The directory to source files from. + /// True to recurse directories, false for no recursion. + /// The file filter to apply. + /// The directory filter to apply. + public void CreateZip(string zipFileName, string sourceDirectory, + bool recurse, IScanFilter fileFilter, IScanFilter directoryFilter) + { + CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, directoryFilter, false); + } + + /// + /// Create a zip archive sending output to the passed. + /// + /// The stream to write archive data to. + /// The directory to source files from. + /// True to recurse directories, false for no recursion. + /// The file filter to apply. + /// The directory filter to apply. + /// true to leave open after the zip has been created, false to dispose it. + public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, IScanFilter fileFilter, IScanFilter directoryFilter, bool leaveOpen = false) + { + var scanner = new FileSystemScanner(fileFilter, directoryFilter); + CreateZip(outputStream, sourceDirectory, recurse, scanner, leaveOpen); + } + + /// + /// Create a zip archive sending output to the passed. + /// + /// The stream to write archive data to. + /// The directory to source files from. + /// True to recurse directories, false for no recursion. + /// For performing the actual file system scan + /// The is closed after creation. + private void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, FileSystemScanner scanner, bool leaveOpen) { NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; @@ -390,7 +433,6 @@ public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, } outputStream_.UseZip64 = UseZip64; - var scanner = new FileSystemScanner(fileFilter, directoryFilter); scanner.ProcessFile += ProcessFile; if (this.CreateEmptyDirectories) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 259bde43b..e3b43d643 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -238,7 +238,7 @@ private void TestFileNames(IEnumerable names) nameCount++; } - zippy.CreateZip(tempZip.Filename, tempDir.Fullpath, true, null, null); + zippy.CreateZip(tempZip.Filename, tempDir.Fullpath, true, null); using (ZipFile z = new ZipFile(tempZip.Filename)) { From 1a47326ffa7a0da9ef99a9e26fd3fde97b482cc6 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 9 Aug 2020 16:59:40 +0100 Subject: [PATCH 036/162] PR #497: Transform new entry names using an INameTranform in ZipOutputStream --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 1 + src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 5 ++ .../Zip/ZipNameTransform.cs | 72 +++++++++++++++++++ .../Zip/ZipOutputStream.cs | 25 +++++++ 4 files changed, 103 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 6c7e106e2..3a8443652 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -426,6 +426,7 @@ private void CreateZip(Stream outputStream, string sourceDirectory, bool recurse { outputStream_.SetLevel((int)CompressionLevel); outputStream_.IsStreamOwner = !leaveOpen; + outputStream_.NameTransform = null; // all required transforms handled by us if (password_ != null) { diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index f119a1c4a..d6e4b98fa 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -782,6 +782,11 @@ public string Name { return name; } + + internal set + { + name = value; + } } /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs index b0c8b72cb..2c0591671 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs @@ -238,4 +238,76 @@ public static bool IsValidName(string name) #endregion Class Fields } + + /// + /// An implementation of INameTransform that transforms entry paths as per the Zip file naming convention. + /// Strips path roots and puts directory separators in the correct format ('/') + /// + public class PathTransformer : INameTransform + { + /// + /// Initialize a new instance of + /// + public PathTransformer() + { + } + + /// + /// Transform a windows directory name according to the Zip file naming conventions. + /// + /// The directory name to transform. + /// The transformed name. + public string TransformDirectory(string name) + { + name = TransformFile(name); + + if (name.Length > 0) + { + if (!name.EndsWith("/", StringComparison.Ordinal)) + { + name += "/"; + } + } + else + { + throw new ZipException("Cannot have an empty directory name"); + } + + return name; + } + + /// + /// Transform a windows file name according to the Zip file naming conventions. + /// + /// The file name to transform. + /// The transformed name. + public string TransformFile(string name) + { + if (name != null) + { + // Put separators in the expected format. + name = name.Replace(@"\", "/"); + + // Remove the path root. + name = WindowsPathUtils.DropPathRoot(name); + + // Drop any leading and trailing slashes. + name = name.Trim('/'); + + // Convert consecutive // characters to / + int index = name.IndexOf("//", StringComparison.Ordinal); + while (index >= 0) + { + name = name.Remove(index, 1); + index = name.IndexOf("//", StringComparison.Ordinal); + } + } + else + { + name = string.Empty; + } + + return name; + } + } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index fe5079e07..1bd544c2d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -1,4 +1,5 @@ using ICSharpCode.SharpZipLib.Checksum; +using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using System; @@ -146,6 +147,12 @@ public UseZip64 UseZip64 set { useZip64_ = value; } } + /// + /// Used for transforming the names of entries added by . + /// Defaults to , set to null to disable transforms and use names as supplied. + /// + public INameTransform NameTransform { get; set; } = new PathTransformer(); + /// /// Write an unsigned short in little endian byte order. /// @@ -182,6 +189,22 @@ private void WriteLeLong(long value) } } + // Apply any configured transforms/cleaning to the name of the supplied entry. + private void TransformEntryName(ZipEntry entry) + { + if (this.NameTransform != null) + { + if (entry.IsDirectory) + { + entry.Name = this.NameTransform.TransformDirectory(entry.Name); + } + else + { + entry.Name = this.NameTransform.TransformFile(entry.Name); + } + } + } + /// /// Starts a new Zip entry. It automatically closes the previous /// entry if present. @@ -367,6 +390,8 @@ public void PutNextEntry(ZipEntry entry) } } + // Apply any required transforms to the entry name, and then convert to byte array format. + TransformEntryName(entry); byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); if (name.Length > 0xFFFF) From cfc51121c7f8136ee2aefcf7516066b39edcb4b6 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 9 Aug 2020 17:03:49 +0100 Subject: [PATCH 037/162] PR #353: Fix ZipFile.TestLocalHeader CompressionMethod resolving for AES entries * Change ZipFile.TestLocalHeader to check CompressionMethodForHeader rather than CompressionMethod. * Test ZipFile.TestArchive with an AES encrypted archive. --- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 2 +- test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 056785e16..c5c05afad 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1216,7 +1216,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } // Central header compression method matches local entry - if (entry.CompressionMethod != (CompressionMethod)compressionMethod) + if (entry.CompressionMethodForHeader != (CompressionMethod)compressionMethod) { throw new ZipException("Central header/local header compression method mismatch"); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index d77e309b0..adb938516 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -105,6 +105,8 @@ public void ZipFileAesDecryption() Assert.AreEqual(DummyDataString, content, "Decompressed content does not match input data"); } } + + Assert.That(zipFile.TestArchive(false), Is.True, "Encrypted archive should pass validation."); } } From 59e30802da5fc3047de5758f2e2ec1cd53d72811 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 9 Aug 2020 17:15:54 +0100 Subject: [PATCH 038/162] PR #380: Add support for AES encryption in FastZip.CreateZip --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 35 ++++++++++++++++++- .../Zip/ZipEncryptionMethod.cs | 28 +++++++++++++++ .../Zip/FastZipHandling.cs | 27 ++++++++++++-- 3 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 src/ICSharpCode.SharpZipLib/Zip/ZipEncryptionMethod.cs diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 3a8443652..1565faf2d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -226,6 +226,15 @@ public string Password set { password_ = value; } } + /// + /// Get / set the method of encrypting entries. + /// + /// + /// Only applies when is set. + /// Defaults to ZipCrypto for backwards compatibility purposes. + /// + public ZipEncryptionMethod EntryEncryptionMethod { get; set; } = ZipEncryptionMethod.ZipCrypto; + /// /// Get or set the active when creating Zip files. /// @@ -428,7 +437,7 @@ private void CreateZip(Stream outputStream, string sourceDirectory, bool recurse outputStream_.IsStreamOwner = !leaveOpen; outputStream_.NameTransform = null; // all required transforms handled by us - if (password_ != null) + if (false == string.IsNullOrEmpty(password_) && EntryEncryptionMethod != ZipEncryptionMethod.None) { outputStream_.Password = password_; } @@ -597,6 +606,10 @@ private void ProcessFile(object sender, ScanEventArgs e) using (FileStream stream = File.Open(e.Name, FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipEntry entry = entryFactory_.MakeFileEntry(e.Name); + + // Set up AES encryption for the entry if required. + ConfigureEntryEncryption(entry); + outputStream_.PutNextEntry(entry); AddFileContents(e.Name, stream); } @@ -616,6 +629,26 @@ private void ProcessFile(object sender, ScanEventArgs e) } } + // Set up the encryption method to use for the specific entry. + private void ConfigureEntryEncryption(ZipEntry entry) + { + // Only alter the entries options if AES isn't already enabled for it + // (it might have been set up by the entry factory, and if so we let that take precedence) + if (!string.IsNullOrEmpty(Password) && entry.AESEncryptionStrength == 0) + { + switch (EntryEncryptionMethod) + { + case ZipEncryptionMethod.AES128: + entry.AESKeySize = 128; + break; + + case ZipEncryptionMethod.AES256: + entry.AESKeySize = 256; + break; + } + } + } + private void AddFileContents(string name, Stream stream) { if (stream == null) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEncryptionMethod.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEncryptionMethod.cs new file mode 100644 index 000000000..ed51559cd --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEncryptionMethod.cs @@ -0,0 +1,28 @@ +namespace ICSharpCode.SharpZipLib.Zip +{ + /// + /// The method of encrypting entries when creating zip archives. + /// + public enum ZipEncryptionMethod + { + /// + /// No encryption will be used. + /// + None, + + /// + /// Encrypt entries with ZipCrypto. + /// + ZipCrypto, + + /// + /// Encrypt entries with AES 128. + /// + AES128, + + /// + /// Encrypt entries with AES 256. + /// + AES256 + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index e3b43d643..753fc8623 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -159,8 +159,11 @@ public void ContentEqualAfterAfterArchived([Values(0, 1, 64)]int contentSize) } [Test] + [TestCase(ZipEncryptionMethod.ZipCrypto)] + [TestCase(ZipEncryptionMethod.AES128)] + [TestCase(ZipEncryptionMethod.AES256)] [Category("Zip")] - public void Encryption() + public void Encryption(ZipEncryptionMethod encryptionMethod) { const string tempName1 = "a.dat"; @@ -174,8 +177,11 @@ public void Encryption() try { - var fastZip = new FastZip(); - fastZip.Password = "Ahoy"; + var fastZip = new FastZip + { + Password = "Ahoy", + EntryEncryptionMethod = encryptionMethod + }; fastZip.CreateZip(target, tempFilePath, false, @"a\.dat", null); @@ -189,6 +195,21 @@ public void Encryption() Assert.AreEqual(1, entry.Size); Assert.IsTrue(zf.TestArchive(true)); Assert.IsTrue(entry.IsCrypted); + + switch (encryptionMethod) + { + case ZipEncryptionMethod.ZipCrypto: + Assert.That(entry.AESKeySize, Is.Zero, "AES key size should be 0 for ZipCrypto encrypted entries"); + break; + + case ZipEncryptionMethod.AES128: + Assert.That(entry.AESKeySize, Is.EqualTo(128), "AES key size should be 128 for AES128 encrypted entries"); + break; + + case ZipEncryptionMethod.AES256: + Assert.That(entry.AESKeySize, Is.EqualTo(256), "AES key size should be 256 for AES256 encrypted entries"); + break; + } } } finally From 33ab19bb5ab9177245b6bc1462db112e1f7f0b76 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 9 Aug 2020 22:35:55 +0100 Subject: [PATCH 039/162] PR #504: Fix warning about missing doc comment in FastZip.CreateZip --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 1565faf2d..cd3bfad4d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -425,6 +425,7 @@ public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, /// The directory to source files from. /// True to recurse directories, false for no recursion. /// For performing the actual file system scan + /// true to leave open after the zip has been created, false to dispose it. /// The is closed after creation. private void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, FileSystemScanner scanner, bool leaveOpen) { From 96b4d86fc37cdfea962cfc78d1cc0053652e8d1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 9 Aug 2020 23:50:33 +0200 Subject: [PATCH 040/162] PR #505: Expect ZipEntry clean name test to be positive --- test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index 1adebe2ab..cb2c72d16 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -286,7 +286,6 @@ public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLengt [Test] [Category("Zip")] - [Category("KnownBugs")] public void ZipEntryFileNameAutoClean() { using (var dummyZip = Utils.GetDummyFile(0)) @@ -295,6 +294,7 @@ public void ZipEntryFileNameAutoClean() using (var zipOutputStream = new ZipOutputStream(zipFileStream)) using (var inputFileStream = File.OpenRead(inputFile.Filename)) { + // New ZipEntry created with a full file name path as it's name zipOutputStream.PutNextEntry(new ZipEntry(inputFile.Filename) { CompressionMethod = CompressionMethod.Stored, @@ -305,11 +305,9 @@ public void ZipEntryFileNameAutoClean() using (var zf = new ZipFile(dummyZip.Filename)) { - Assert.AreNotEqual(ZipEntry.CleanName(inputFile.Filename), zf[0].Name, - "Entry file name \"{0}\" WAS automatically cleaned, this test should be removed", inputFile.Filename); + // The ZipEntry name should have been automatically cleaned + Assert.AreEqual(ZipEntry.CleanName(inputFile.Filename), zf[0].Name); } - - Assert.Warn("Entry file name \"{0}\" was not automatically cleaned", inputFile.Filename); } } From 63e7e70d9c4a3811d090c221effc760f0262d6d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 15 Aug 2020 11:58:11 +0200 Subject: [PATCH 041/162] Use github workflows for CI (#419) * Add Github Actions workflows * Use VS 2019 in AppVeyor CI --- .editorconfig | 4 + .github/workflows/on-push.yml | 79 ++++++ .github/workflows/pull-request.yml | 93 +++++++ appveyor.yml | 4 +- .../ICSharpCode.SharpZipLib.Tests.csproj | 2 +- .../Zip/ZipEntryFactoryHandling.cs | 240 ++++++++++++------ 6 files changed, 340 insertions(+), 82 deletions(-) create mode 100644 .github/workflows/on-push.yml create mode 100644 .github/workflows/pull-request.yml diff --git a/.editorconfig b/.editorconfig index 92cbdb1d6..5b84cc53b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -33,3 +33,7 @@ indent_size = 2 end_of_line = lf [*.{cmd, bat}] end_of_line = crlf + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml new file mode 100644 index 000000000..45a56e0d1 --- /dev/null +++ b/.github/workflows/on-push.yml @@ -0,0 +1,79 @@ +name: Build master on push + +env: + PUBLISH_DEV_PACKS: disabled + +on: + push: + branches: [ master ] + +jobs: + BuildAndTest: + runs-on: ${{ matrix.os }}-latest + strategy: + fail-fast: false + matrix: + configuration: [debug, release] + os: [ubuntu, windows, macos] + libtarget: [netstandard2] + testtarget: [netcoreapp3.1] + include: + - configuration: debug + os: windows + libtarget: net45 + testtarget: net45 + - configuration: release + os: windows + libtarget: net45 + testtarget: net45 + steps: + - uses: actions/checkout@v2 + + - name: Setup .NET Core + if: matrix.libtarget == 'netstandard2' + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + + - name: Build library + run: dotnet build -c ${{ matrix.configuration }} -f ${{ matrix.libtarget }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + + - name: Restore test dependencies + run: dotnet restore + + - name: Run tests + run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.testtarget }} --no-restore + + + Package: + if: env.PUBLISH_DEV_PACKS != 'disabled' + needs: [BuildAndTest] + runs-on: windows-latest + env: + NUGET_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} + + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + source-url: https://nuget.pkg.github.com/icsharpcode/index.json + + - name: Build library for .NET Standard 2 + run: dotnet build -c Release -f netstandard2 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library for .NET Framework 4.5 + run: dotnet build -c Release -f net45 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + + - name: Create nuget package + run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:Version=$(git describe --abbrev | % { $_.substring(1) }) + + - name: Show package name + run: ls dist\*.nupkg + + - name: Publish the package to GPR + if: env.PUBLISH_DEV_PACKS == 'enabled' + run: dotnet nuget push dist\*.nupkg diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml new file mode 100644 index 000000000..72f6556d2 --- /dev/null +++ b/.github/workflows/pull-request.yml @@ -0,0 +1,93 @@ +name: Build and Test PR + +on: + pull_request: + branches: [ master ] + +jobs: + Build: + runs-on: ${{ matrix.os }}-latest + strategy: + fail-fast: false + matrix: + configuration: [debug, release] + os: [ubuntu, windows, macos] + target: [netstandard2] + include: + - configuration: Debug + os: windows + target: net45 + - configuration: Release + os: windows + target: net45 + steps: + - uses: actions/checkout@v2 + + - name: Setup .NET Core + if: matrix.target == 'netstandard2' + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + + - name: Build library + run: dotnet build -c ${{ matrix.configuration }} -f ${{ matrix.target }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + + Test: + runs-on: ${{ matrix.os }}-latest + strategy: + fail-fast: false + matrix: + configuration: [debug, release] + os: [ubuntu, windows, macos] + target: [netcoreapp3.1] + include: + - configuration: debug + os: windows + target: net45 + - configuration: release + os: windows + target: net45 + steps: + - uses: actions/checkout@v2 + + - name: Setup .NET Core + if: matrix.target == 'netcoreapp3.1' + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + + - name: Restore test dependencies + run: dotnet restore + + - name: Run tests + run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.target }} --no-restore + + Pack: + needs: [Build, Test] + runs-on: windows-latest + env: + NUGET_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} + + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + + - name: Build library for .NET Standard 2 + run: dotnet build -c Release -f netstandard2 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library for .NET Framework 4.5 + run: dotnet build -c Release -f net45 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + + - name: Create nuget package + run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:Version=$(git describe --abbrev | % { $_.substring(1) })-PR + + - name: Upload nuget package artifact + uses: actions/upload-artifact@v2 + with: + name: Nuget package + path: dist/*.nupkg diff --git a/appveyor.yml b/appveyor.yml index a6197ff29..df3ffb4ba 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,5 +1,5 @@ version: '{build}' -image: Visual Studio 2017 +image: Visual Studio 2019 configuration: - Debug - Release @@ -31,4 +31,4 @@ test_script: artifacts: - path: docs\help\_site type: zip - name: Documentation \ No newline at end of file + name: Documentation diff --git a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj index fa214385c..bf9e5b926 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj +++ b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj @@ -2,7 +2,7 @@ Library - netcoreapp2.0;net46 + netcoreapp3.1;net46 diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs index c1ba17f64..5a892abde 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEntryFactoryHandling.cs @@ -87,99 +87,181 @@ public void CreateInMemoryValues() [Test] [Category("Zip")] [Category("CreatesTempFile")] - public void CreatedValues() + [Platform("Win32NT")] + public void CreatedFileEntriesUsesExpectedAttributes() { string tempDir = GetTempFilePath(); - Assert.IsNotNull(tempDir, "No permission to execute this test?"); + if (tempDir == null) Assert.Inconclusive("No permission to execute this test?"); tempDir = Path.Combine(tempDir, "SharpZipTest"); + Directory.CreateDirectory(tempDir); - if (tempDir != null) + try { - Directory.CreateDirectory(tempDir); + string tempFile = Path.Combine(tempDir, "SharpZipTest.Zip"); + + using (FileStream f = File.Create(tempFile, 1024)) + { + f.WriteByte(0); + } + + FileAttributes attributes = FileAttributes.Hidden; + + File.SetAttributes(tempFile, attributes); + ZipEntryFactory factory = null; + ZipEntry entry; + int combinedAttributes = 0; try { - // Note the seconds returned will be even! - var createTime = new DateTime(2100, 2, 27, 11, 07, 56); - var lastWriteTime = new DateTime(2050, 11, 3, 7, 23, 32); - var lastAccessTime = new DateTime(2050, 11, 3, 0, 42, 12); - - string tempFile = Path.Combine(tempDir, "SharpZipTest.Zip"); - - using (FileStream f = File.Create(tempFile, 1024)) - { - f.WriteByte(0); - } - - File.SetCreationTime(tempFile, createTime); - File.SetLastWriteTime(tempFile, lastWriteTime); - File.SetLastAccessTime(tempFile, lastAccessTime); - - FileAttributes attributes = FileAttributes.Hidden; - - File.SetAttributes(tempFile, attributes); - ZipEntryFactory factory = null; - ZipEntry entry; - int combinedAttributes = 0; - - try - { - factory = new ZipEntryFactory(); - - factory.Setting = ZipEntryFactory.TimeSetting.CreateTime; - factory.GetAttributes = ~((int)FileAttributes.ReadOnly); - factory.SetAttributes = (int)FileAttributes.ReadOnly; - combinedAttributes = (int)(FileAttributes.ReadOnly | FileAttributes.Hidden); - - entry = factory.MakeFileEntry(tempFile); - Assert.AreEqual(createTime, entry.DateTime, "Create time failure"); - Assert.AreEqual(entry.ExternalFileAttributes, combinedAttributes); - Assert.AreEqual(1, entry.Size); - - factory.Setting = ZipEntryFactory.TimeSetting.LastAccessTime; - entry = factory.MakeFileEntry(tempFile); - Assert.AreEqual(lastAccessTime, entry.DateTime, "Access time failure"); - Assert.AreEqual(1, entry.Size); - - factory.Setting = ZipEntryFactory.TimeSetting.LastWriteTime; - entry = factory.MakeFileEntry(tempFile); - Assert.AreEqual(lastWriteTime, entry.DateTime, "Write time failure"); - Assert.AreEqual(1, entry.Size); - } - finally - { - File.Delete(tempFile); - } - - // Do the same for directories - // Note the seconds returned will be even! - createTime = new DateTime(2090, 2, 27, 11, 7, 56); - lastWriteTime = new DateTime(2107, 12, 31, 23, 59, 58); - lastAccessTime = new DateTime(1980, 1, 1, 1, 0, 0); - - Directory.SetCreationTime(tempDir, createTime); - Directory.SetLastWriteTime(tempDir, lastWriteTime); - Directory.SetLastAccessTime(tempDir, lastAccessTime); - - factory.Setting = ZipEntryFactory.TimeSetting.CreateTime; - entry = factory.MakeDirectoryEntry(tempDir); - Assert.AreEqual(createTime, entry.DateTime, "Directory create time failure"); - Assert.IsTrue((entry.ExternalFileAttributes & (int)FileAttributes.Directory) == (int)FileAttributes.Directory); - - factory.Setting = ZipEntryFactory.TimeSetting.LastAccessTime; - entry = factory.MakeDirectoryEntry(tempDir); - Assert.AreEqual(lastAccessTime, entry.DateTime, "Directory access time failure"); - - factory.Setting = ZipEntryFactory.TimeSetting.LastWriteTime; - entry = factory.MakeDirectoryEntry(tempDir); - Assert.AreEqual(lastWriteTime, entry.DateTime, "Directory write time failure"); + factory = new ZipEntryFactory(); + + factory.GetAttributes = ~((int)FileAttributes.ReadOnly); + factory.SetAttributes = (int)FileAttributes.ReadOnly; + combinedAttributes = (int)(FileAttributes.ReadOnly | FileAttributes.Hidden); + + entry = factory.MakeFileEntry(tempFile); + Assert.AreEqual(entry.ExternalFileAttributes, combinedAttributes); + Assert.AreEqual(1, entry.Size); } finally { - Directory.Delete(tempDir, true); + File.Delete(tempFile); } } + finally + { + Directory.Delete(tempDir, true); + } + + } + + [Test] + [Category("Zip")] + [Category("CreatesTempFile")] + [TestCase(ZipEntryFactory.TimeSetting.CreateTime)] + [TestCase(ZipEntryFactory.TimeSetting.LastAccessTime)] + [TestCase(ZipEntryFactory.TimeSetting.LastWriteTime)] + public void CreatedFileEntriesUsesExpectedTime(ZipEntryFactory.TimeSetting timeSetting) + { + string tempDir = GetTempFilePath(); + if (tempDir == null) Assert.Inconclusive("No permission to execute this test?"); + + tempDir = Path.Combine(tempDir, "SharpZipTest"); + + // Note the seconds returned will be even! + var expectedTime = new DateTime(2100, 2, 27, 11, 07, 56); + + Directory.CreateDirectory(tempDir); + + try + { + + string tempFile = Path.Combine(tempDir, "SharpZipTest.Zip"); + + using (FileStream f = File.Create(tempFile, 1024)) + { + f.WriteByte(0); + } + + DateTime fileTime = DateTime.MinValue; + + if (timeSetting == ZipEntryFactory.TimeSetting.CreateTime) { + File.SetCreationTime(tempFile, expectedTime); + fileTime = File.GetCreationTime(tempFile); + } + + if (timeSetting == ZipEntryFactory.TimeSetting.LastAccessTime){ + File.SetLastAccessTime(tempFile, expectedTime); + fileTime = File.GetLastAccessTime(tempFile); + } + + if (timeSetting == ZipEntryFactory.TimeSetting.LastWriteTime) { + File.SetLastWriteTime(tempFile, expectedTime); + fileTime = File.GetLastWriteTime(tempFile); + } + + if(fileTime != expectedTime) { + Assert.Inconclusive("File time could not be altered"); + } + + var factory = new ZipEntryFactory(); + + factory.Setting = timeSetting; + + var entry = factory.MakeFileEntry(tempFile); + Assert.AreEqual(expectedTime, entry.DateTime); + Assert.AreEqual(1, entry.Size); + + } + finally + { + Directory.Delete(tempDir, true); + } + + } + + [Test] + [Category("Zip")] + [Category("CreatesTempFile")] + [TestCase(ZipEntryFactory.TimeSetting.CreateTime)] + [TestCase(ZipEntryFactory.TimeSetting.LastAccessTime)] + [TestCase(ZipEntryFactory.TimeSetting.LastWriteTime)] + public void CreatedDirectoryEntriesUsesExpectedTime(ZipEntryFactory.TimeSetting timeSetting) + { + string tempDir = GetTempFilePath(); + if (tempDir == null) Assert.Inconclusive("No permission to execute this test?"); + + tempDir = Path.Combine(tempDir, "SharpZipTest"); + + // Note the seconds returned will be even! + var expectedTime = new DateTime(2100, 2, 27, 11, 07, 56); + + Directory.CreateDirectory(tempDir); + + try + { + + string tempFile = Path.Combine(tempDir, "SharpZipTest.Zip"); + + using (FileStream f = File.Create(tempFile, 1024)) + { + f.WriteByte(0); + } + + DateTime dirTime = DateTime.MinValue; + + if (timeSetting == ZipEntryFactory.TimeSetting.CreateTime) { + Directory.SetCreationTime(tempFile, expectedTime); + dirTime = Directory.GetCreationTime(tempDir); + } + + if (timeSetting == ZipEntryFactory.TimeSetting.LastAccessTime){ + Directory.SetLastAccessTime(tempDir, expectedTime); + dirTime = Directory.GetLastAccessTime(tempDir); + } + + if (timeSetting == ZipEntryFactory.TimeSetting.LastWriteTime) { + Directory.SetLastWriteTime(tempDir, expectedTime); + dirTime = Directory.GetLastWriteTime(tempDir); + } + + if(dirTime != expectedTime) { + Assert.Inconclusive("Directory time could not be altered"); + } + + var factory = new ZipEntryFactory(); + + factory.Setting = timeSetting; + + var entry = factory.MakeDirectoryEntry(tempDir); + Assert.AreEqual(expectedTime, entry.DateTime); + } + finally + { + Directory.Delete(tempDir, true); + } + } } } From c55726601307b4f03d3186feb3fed1b232d5ed4e Mon Sep 17 00:00:00 2001 From: Stevie-O Date: Sat, 15 Aug 2020 07:16:21 -0400 Subject: [PATCH 042/162] PR #201: Raise ProcessDirectory event for FastZip extract FastZip's ExtractZip method did not raise the ProcessDirectory event when creating a directory. There was no way to determine or control when ExtractZip decided to create a new directory. NOTE: The logic to raise the event only triggers when the target directory doesn't already exist in the destination. --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index cd3bfad4d..348527e4f 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -783,7 +783,7 @@ private void ExtractEntry(ZipEntry entry) // TODO: Fire delegate/throw exception were compression method not supported, or name is invalid? - string dirName = null; + string dirName = string.Empty; if (doExtraction) { @@ -803,11 +803,18 @@ private void ExtractEntry(ZipEntry entry) { try { - Directory.CreateDirectory(dirName); - - if (entry.IsDirectory && restoreDateTimeOnExtract_) + continueRunning_ = events_?.OnProcessDirectory(dirName, true) ?? true; + if (continueRunning_) + { + Directory.CreateDirectory(dirName); + if (entry.IsDirectory && restoreDateTimeOnExtract_) + { + Directory.SetLastWriteTime(dirName, entry.DateTime); + } + } + else { - Directory.SetLastWriteTime(dirName, entry.DateTime); + doExtraction = false; } } catch (Exception ex) From 83c80d2c9bf0a50f30b0899d1be1961d6bb7fcc4 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 15 Aug 2020 12:24:07 +0100 Subject: [PATCH 043/162] PR #333: Handle unsupported compression methods in ZipInputStream better MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Change ZipInputStream to use its own IsEntryCompressionMethodSupported function rather than the one in ZipEntry. * Unit test for ZipInputStream.CanDecompressEntry being false for AES encrypted entries. * Fix comment typo Co-authored-by: nils måsén --- .../Zip/ZipInputStream.cs | 20 +++++++++-- .../Zip/ZipEncryptionHandling.cs | 34 +++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs index 147d4043d..66a3fc872 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs @@ -131,10 +131,26 @@ public bool CanDecompressEntry { get { - return (entry != null) && entry.CanDecompress; + return (entry != null) && IsEntryCompressionMethodSupported(entry) && entry.CanDecompress; } } + /// + /// Is the compression method for the specified entry supported? + /// + /// + /// Uses entry.CompressionMethodForHeader so that entries of type WinZipAES will be rejected. + /// + /// the entry to check. + /// true if the compression methiod is supported, false if not. + private static bool IsEntryCompressionMethodSupported(ZipEntry entry) + { + var entryCompressionMethod = entry.CompressionMethodForHeader; + + return entryCompressionMethod == CompressionMethod.Deflated || + entryCompressionMethod == CompressionMethod.Stored; + } + /// /// Advances to the next entry in the archive /// @@ -271,7 +287,7 @@ public ZipEntry GetNextEntry() } // Determine how to handle reading of data if this is attempted. - if (entry.IsCompressionMethodSupported()) + if (IsEntryCompressionMethodSupported(entry)) { internalReader = new ReadDataHandler(InitialRead); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index adb938516..49317207c 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -437,6 +437,40 @@ public void ZipFileAESReadWithEmptyPassword() } } + /// + /// ZipInputStream can't decrypt AES encrypted entries, but it should report that to the caller + /// rather than just failing. + /// + [Test] + [Category("Zip")] + public void ZipinputStreamShouldGracefullyFailWithAESStreams() + { + string password = "password"; + + using (var memoryStream = new MemoryStream()) + { + // Try to create a zip stream + WriteEncryptedZipToStream(memoryStream, password, 256); + + // reset + memoryStream.Seek(0, SeekOrigin.Begin); + + // Try to read + using (var inputStream = new ZipInputStream(memoryStream)) + { + inputStream.Password = password; + var entry = inputStream.GetNextEntry(); + Assert.That(entry.AESKeySize, Is.EqualTo(256), "Test entry should be AES256 encrypted."); + + // CanDecompressEntry should be false. + Assert.That(inputStream.CanDecompressEntry, Is.False, "CanDecompressEntry should be false for AES encrypted entries"); + + // Should throw on read. + Assert.Throws(() => inputStream.ReadByte()); + } + } + } + private static readonly string[] possible7zPaths = new[] { // Check in PATH "7z", "7za", From 69ce65cd672505a1ae5ffd4e15aa1f009ba3819a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 15 Aug 2020 13:54:10 +0200 Subject: [PATCH 044/162] PR #346: Add a Security Policy --- SECURITY.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 000000000..1829e8c5b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 1.3.x | :white_check_mark: | +| 1.2.x | :white_check_mark: | +| 1.1.x | :white_check_mark: | +| 1.0.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +Send an e-mail to sharpziplib@containrrr.dev From 118fa32ea6bc4ea7a973c766e06db3475acb4689 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 16 Aug 2020 12:29:00 +0200 Subject: [PATCH 045/162] Fix master on-push workflow --- .github/workflows/on-push.yml | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 45a56e0d1..7c772c051 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -46,7 +46,6 @@ jobs: Package: - if: env.PUBLISH_DEV_PACKS != 'disabled' needs: [BuildAndTest] runs-on: windows-latest env: @@ -69,11 +68,10 @@ jobs: run: dotnet build -c Release -f net45 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - name: Create nuget package - run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:Version=$(git describe --abbrev | % { $_.substring(1) }) + run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:ContinuousIntegrationBuild=true /p:Version=$(git describe --abbrev | % { $_.substring(1) }) - - name: Show package name - run: ls dist\*.nupkg - - - name: Publish the package to GPR - if: env.PUBLISH_DEV_PACKS == 'enabled' - run: dotnet nuget push dist\*.nupkg + - name: Upload nuget package artifact + uses: actions/upload-artifact@v2 + with: + name: Nuget package + path: dist/*.nupkg From 33cf8c4ccee14adbe6635d2c6d7534b6d10c474a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 16 Aug 2020 13:02:47 +0200 Subject: [PATCH 046/162] Make healthy sourcelink nupkgs --- .github/workflows/on-push.yml | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 7c772c051..92295d56a 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -62,13 +62,8 @@ jobs: dotnet-version: '3.1.x' source-url: https://nuget.pkg.github.com/icsharpcode/index.json - - name: Build library for .NET Standard 2 - run: dotnet build -c Release -f netstandard2 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - - name: Build library for .NET Framework 4.5 - run: dotnet build -c Release -f net45 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - - - name: Create nuget package - run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:ContinuousIntegrationBuild=true /p:Version=$(git describe --abbrev | % { $_.substring(1) }) + - name: Build and pack + run: dotnet build -c Release -o dist /p:ContinuousIntegrationBuild=true /p:EmbedUntrackedSources=true /p:Version=$(git describe --abbrev | % { $_.substring(1) }) src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - name: Upload nuget package artifact uses: actions/upload-artifact@v2 From a6cdf092f7e535cd9996a301390e6e5a0b333940 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 16 Aug 2020 13:55:10 +0100 Subject: [PATCH 047/162] PR #451: Minimize and update sample app package dependencies --- .../cs/Cmd_BZip2/Cmd_BZip2.csproj | 85 +------------------ .../cs/Cmd_BZip2/packages.config | 48 +---------- .../cs/Cmd_Checksum/Cmd_Checksum.cs | 6 +- .../cs/Cmd_Checksum/Cmd_Checksum.csproj | 80 +---------------- .../cs/Cmd_Checksum/packages.config | 48 +---------- .../cs/Cmd_GZip/Cmd_GZip.csproj | 80 +---------------- .../cs/Cmd_GZip/packages.config | 48 +---------- .../cs/Cmd_Tar/Cmd_Tar.csproj | 80 +---------------- .../cs/Cmd_Tar/packages.config | 48 +---------- .../cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj | 80 +---------------- .../cs/Cmd_ZipInfo/packages.config | 48 +---------- .../cs/CreateZipFile/CreateZipFile.csproj | 80 +---------------- .../cs/CreateZipFile/packages.config | 48 +---------- .../cs/FastZip/FastZip.csproj | 79 ----------------- .../cs/FastZip/packages.config | 48 +---------- .../cs/sz/packages.config | 48 +---------- .../cs/sz/sz.cs | 4 +- .../cs/sz/sz.csproj | 80 +---------------- .../cs/unzipfile/packages.config | 48 +---------- .../cs/unzipfile/unzipfile.csproj | 80 +---------------- .../cs/viewzipfile/packages.config | 48 +---------- .../cs/viewzipfile/viewzipfile.csproj | 80 +---------------- .../cs/zf/packages.config | 48 +---------- .../cs/zf/zf.cs | 4 +- .../cs/zf/zf.csproj | 80 +---------------- 25 files changed, 38 insertions(+), 1388 deletions(-) diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj index 351f801f9..b1428fe16 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj @@ -80,84 +80,10 @@ copy Cmd_BZip2.exe bunzip2.exe 4096 - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -178,11 +104,4 @@ copy Cmd_BZip2.exe bunzip2.exe - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.cs b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.cs index 49426af69..c40ede339 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.cs +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.cs @@ -132,7 +132,7 @@ public static int Main(string[] args) case Command.Crc32: var currentCrc = new Crc32(); while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) { - currentCrc.Update(buffer, 0, bytesRead); + currentCrc.Update(new ArraySegment(buffer, 0, bytesRead)); } Console.WriteLine("CRC32 for {0} is 0x{1:X8}", args[0], currentCrc.Value); break; @@ -140,7 +140,7 @@ public static int Main(string[] args) case Command.BZip2: var currentBZip2Crc = new BZip2Crc(); while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) { - currentBZip2Crc.Update(buffer, 0, bytesRead); + currentBZip2Crc.Update(new ArraySegment(buffer, 0, bytesRead)); } Console.WriteLine("BZip2CRC32 for {0} is 0x{1:X8}", args[0], currentBZip2Crc.Value); break; @@ -148,7 +148,7 @@ public static int Main(string[] args) case Command.Adler: var currentAdler = new Adler32(); while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0) { - currentAdler.Update(buffer, 0, bytesRead); + currentAdler.Update(new ArraySegment(buffer, 0, bytesRead)); } Console.WriteLine("Adler32 for {0} is 0x{1:X8}", args[0], currentAdler.Value); break; diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj index 25d80e70b..c47abeba1 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj @@ -74,84 +74,15 @@ true - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -172,11 +103,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj index 825bc2cc1..50e9b8d5d 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj @@ -74,84 +74,15 @@ copy Cmd_GZip.exe gunzip.exe true - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -172,11 +103,4 @@ copy Cmd_GZip.exe gunzip.exe - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj index db8910d00..7908ee9b8 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj @@ -66,86 +66,17 @@ Cmd_Tar - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -166,11 +97,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj index 12e856069..b2bea17e4 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj @@ -73,84 +73,15 @@ true - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -171,11 +102,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj index ed2046a94..c6ecc7c43 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj @@ -81,84 +81,15 @@ - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -179,11 +110,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj index 7e52bb16f..5bcd65546 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj @@ -67,84 +67,12 @@ ..\bin\FastZip.XML - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True - - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -162,11 +90,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.cs b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.cs index d928f8907..7a1d10a1b 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.cs +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.cs @@ -294,7 +294,7 @@ bool SetArgs(string[] args) { try { int enc = int.Parse(optArg); if (Encoding.GetEncoding(enc) != null) { - ZipConstants.DefaultCodePage = enc; + ZipStrings.CodePage = enc; } else { result = false; Console.WriteLine("Invalid encoding " + args[argIndex]); @@ -306,7 +306,7 @@ bool SetArgs(string[] args) { } } else { try { - ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage; + ZipStrings.CodePage = Encoding.GetEncoding(optArg).CodePage; } catch (Exception) { result = false; diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj index 864be9d84..6348aa8cf 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj @@ -62,84 +62,15 @@ false - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -157,11 +88,4 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config index d353d1619..0eb486c15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config @@ -1,50 +1,4 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj index 1566ae6f4..124d295ed 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj @@ -38,88 +38,19 @@ UnZipFileClass - - ..\..\packages\SharpZipLib.1.0.0-alpha1\lib\netstandard1.3\ICSharpCode.SharpZipLib.dll - True - - - ..\..\packages\Microsoft.Win32.Primitives.4.3.0\lib\net46\Microsoft.Win32.Primitives.dll - True + + ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll - - ..\..\packages\System.AppContext.4.3.0\lib\net46\System.AppContext.dll - True - - - ..\..\packages\System.Console.4.3.0\lib\net46\System.Console.dll - True - - - ..\..\packages\System.Diagnostics.DiagnosticSource.4.3.0\lib\net46\System.Diagnostics.DiagnosticSource.dll - True - - - ..\..\packages\System.Globalization.Calendars.4.3.0\lib\net46\System.Globalization.Calendars.dll - True - - - ..\..\packages\System.IO.Compression.4.3.0\lib\net46\System.IO.Compression.dll - True - - - ..\..\packages\System.IO.Compression.ZipFile.4.3.0\lib\net46\System.IO.Compression.ZipFile.dll - True - - - ..\..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll - True - - - ..\..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll - True - - - ..\..\packages\System.Net.Http.4.1.2\lib\net46\System.Net.Http.dll - True - - - ..\..\packages\System.Net.Sockets.4.3.0\lib\net46\System.Net.Sockets.dll - True - - - ..\..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll - True - - - ..\..\packages\System.Security.Cryptography.Algorithms.4.2.0\lib\net461\System.Security.Cryptography.Algorithms.dll - True - - - ..\..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll - True - - - ..\..\packages\System.Security.Cryptography.Primitives.4.0.0\lib\net46\System.Security.Cryptography.Primitives.dll - True - - - ..\..\packages\System.Security.Cryptography.X509Certificates.4.1.0\lib\net461\System.Security.Cryptography.X509Certificates.dll - True - - - ..\..\packages\System.Xml.ReaderWriter.4.3.0\lib\net46\System.Xml.ReaderWriter.dll - True - @@ -133,13 +64,6 @@ - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - 1.2.0.7 - 1.2.0.7 - 1.2.0 + 1.3.0.8 + 1.2.0.8 + 1.3.0 SharpZipLib ICSharpCode ICSharpCode @@ -22,11 +22,11 @@ http://icsharpcode.github.io/SharpZipLib/ http://icsharpcode.github.io/SharpZipLib/assets/sharpziplib-nuget-256x256.png https://github.com/icsharpcode/SharpZipLib - Copyright © 2000-2019 SharpZipLib Contributors + Copyright © 2000-2020 SharpZipLib Contributors Compression Library Zip GZip BZip2 LZW Tar en-US -Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.2 for more information. +Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3 for more information. https://github.com/icsharpcode/SharpZipLib From a43d9acf02b2f1deb93d3b2faa7a3dcec01a273a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 8 Oct 2020 10:51:41 +0200 Subject: [PATCH 052/162] Add Codacy to PR workflow --- .github/workflows/pull-request.yml | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 72f6556d2..57b2cea10 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -61,7 +61,16 @@ jobs: - name: Run tests run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.target }} --no-restore - + + Codacy-Analysis: + runs-on: ubuntu-latest + name: Codacy Analysis CLI + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Run codacy-analysis-cli + uses: codacy/codacy-analysis-cli-action@@1.0.1 + Pack: needs: [Build, Test] runs-on: windows-latest From 4f56780f728de2701f9a375f7710599922f0bcfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 8 Oct 2020 10:52:40 +0200 Subject: [PATCH 053/162] Add Codacy to Push workflow --- .github/workflows/on-push.yml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 92295d56a..c0ed8597e 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -44,7 +44,15 @@ jobs: - name: Run tests run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.testtarget }} --no-restore - + Codacy-Analysis: + runs-on: ubuntu-latest + name: Codacy Analysis CLI + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Run codacy-analysis-cli + uses: codacy/codacy-analysis-cli-action@@1.0.1 + Package: needs: [BuildAndTest] runs-on: windows-latest From d6735bd328de835fe7cff440fb69269a9e04e81f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 8 Oct 2020 11:09:52 +0200 Subject: [PATCH 054/162] Fix typo in Push workflow --- .github/workflows/on-push.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index c0ed8597e..e0ceb6ba6 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -51,7 +51,7 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - name: Run codacy-analysis-cli - uses: codacy/codacy-analysis-cli-action@@1.0.1 + uses: codacy/codacy-analysis-cli-action@1.0.1 Package: needs: [BuildAndTest] From b1561a0c4771978e53e632e15d63d6537d14bd47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 8 Oct 2020 17:10:47 +0200 Subject: [PATCH 055/162] PR #523: Fix Codacy workflows * Fix typo and set max allowed to 9999 * Add codacy config * Update on-push.yml * Add project token to Push WF * Add project token to PR WF * Add Codacy upload to push WF * Add Codacy upload to PR WF --- .codacy.yaml | 3 +++ .github/workflows/on-push.yml | 5 +++++ .github/workflows/pull-request.yml | 7 ++++++- 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 .codacy.yaml diff --git a/.codacy.yaml b/.codacy.yaml new file mode 100644 index 000000000..28293b226 --- /dev/null +++ b/.codacy.yaml @@ -0,0 +1,3 @@ +--- +exclude_paths: + - 'docs/**/*' diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index e0ceb6ba6..cb5c48119 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -52,6 +52,11 @@ jobs: uses: actions/checkout@v2 - name: Run codacy-analysis-cli uses: codacy/codacy-analysis-cli-action@1.0.1 + with: + # The current issues needs to be fixed before this can be removed + max-allowed-issues: 9999 + project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} + upload: true Package: needs: [BuildAndTest] diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 57b2cea10..1637f4579 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -69,7 +69,12 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - name: Run codacy-analysis-cli - uses: codacy/codacy-analysis-cli-action@@1.0.1 + uses: codacy/codacy-analysis-cli-action@1.0.1 + with: + # The current issues needs to be fixed before this can be removed + max-allowed-issues: 9999 + project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} + upload: true Pack: needs: [Build, Test] From 6ffe3c1698e88315a418fc5b6f0d087d5553148a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 8 Oct 2020 17:20:49 +0200 Subject: [PATCH 056/162] PR #522: Use PackageIcon instead of PackageIconUrl in csproj * Update ICSharpCode.SharpZipLib.csproj * Add nuget icon * Fix assets path --- assets/sharpziplib-nuget-256x256.png | Bin 0 -> 5435 bytes .../ICSharpCode.SharpZipLib.csproj | 9 ++++++++- 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 assets/sharpziplib-nuget-256x256.png diff --git a/assets/sharpziplib-nuget-256x256.png b/assets/sharpziplib-nuget-256x256.png new file mode 100644 index 0000000000000000000000000000000000000000..60b3a8dae4021d51356ffcb25261306cc14afa58 GIT binary patch literal 5435 zcmX|Fc|6o#_rIT+VFuaPEE&5ZDr9FY*|!*xeI2r|MYf5`k~PYjr3l$0OR^P7z9hSd ziLa0~+l+O7p67YJet(^F?z#88&OPsY&pG$Tn;2=+Qgc!R0BCh}G))13&R7VbD9?yZ zKpF0goDaHT8D!>*3%chR;0n}Se4Sj;y55d%uBNVzE}{N?u1Wx~{M6M{!-o7=dtsQ! z-NV`&rX4n~;YCMz)XlLKFIXuVAMMAXulbf$a6B0gPgCj_N0~UC7ljd3n>FbYudyDUFgVOH-;}V_wfEkO)S`MEr}3oq5x_?l5@D@H zu!zP^@r{IJrdX-3@(pH=mcKUmL9GhmD5j0kp>~P!(Jf;ZQ#JQMA|u{%Czxt?dSoI` zgJzS{AECdpn!$wlLyf|exE&~8+Hz~**SI4VyQQ!JpfdHL{;hlofe^;${R2R9ICC&*-#Bq_N2yI0SeN{t4J`?et| zSh0ElhH*-~)>h~``zNCt1p=fZ`tvkPqmyw7?%env#R7LbxFHejtx4h*%w%i*O- z1x9m5%*UzFd4bZgtS$&~fwZ@~9-^K`zx%T@+&m0RRCktaQ7*#mJ1XpXxR)yy!4xOpgKSBIb?D@LW`07?2V_6fA6DtOUCh2`o!|UTV~uFs8byf>IVMHtCy) z@GJt-?{i{;+7TUoiWlw0ZZZm8If5fLU=7@$UKK-YW`$~XTAMhzv0S zlX;8aX8ef~9saATLB43@e)_-h+PupNoy9fj6N=@i54(S0?1LX@CfyV$+z&~)J|}+% zoXJNAHSN0X$A4DU3;60MU$0(IJjwZ{vMIuP zeV6%Knc(P+ykhaF!l6IMzL~_MK?iMBvzcgu{ca_l##7PKk!HWNU$;_UDs!buKK688 zBPXWp+iL?Oa=%gQ%9M^7zTQ5F0d$Pu&+{M&RVN*PzKV%c4NyKdrc^naN!-${dfW!x z9l`s<{4#4g2A*?Wx6U>XP)yQ6)&%{{b~yNyLNyl9tgj6?uP!~S)LznuT<+O_pNjf5 z(A1K(IP^sb{4s%iQ%>IZeYEnQ-CLdvoN%M>uyL2lSc9XXCZ@>FJ!TpYMG{Y zqn56+oqW8Je06Q%^Ol~b)P#57%tGUHPRQmx-tl7RWr@hQ;=Mjq)R=Y_LO5rZLhIP} zYhaptrA2H|=613i*WLLVx;eY%tkztU>U-IWNJDO+CB9Xsu%BrT<%T3*r%)=BC2{%M z^!^kpwX`E4;sA>&d+N9T->}ubCmpITRcP^f!6PM?rqbe!;cXuGkqNyV*l{5-HnjLB2Oz_abiR998wf(S{-N@HFkEx3sExDYdIVY})6fd`znIQCFJv8yC?>TY z|I*eXYGlOi!bgu%&hZ*RxbugEgbKK#sUbqmE`Y7Lm}XP_q@?xjuY;8#riDz3!pCP_ zi?)X){V7i6V71_M(lA9yWx~NQaYC4t3ZUKea$jrLv~45p>E+v8^8f*WbG23)Eu}}5 zh;PY?ysO~Pi~zCD|Dksh|$4ll1hgYCZsFTy+ z#V&j{zS9KhmsC;kyT`)*RpzXei*ndZqutap^U+9ZaN44JZ~wzg=ZGIjW%NL~orVz<_tE*A%I~I25#HS*~V*0yJvUZE@TB<))d(V0OQRxIH(z4(!y_ zNq2DEh-w2RK{<~?j$h_lgOpE3RqWnNNp*B@Hmkp$DRL6G-1qf;5C!_-1uzKX zPM(Zpeu2Ba9ciiBwS3{>kA>^nu%RahR-y;0Zcw#$fX>C^G-9j9Lo-c`B7<-6Z-9%| zhrBFzOwK&MJ*W9S<-=SeYFTAeGq0*&sLO#HoUP)KHdZ+-Olxq@9tlm_8vILa;2C9; z&3!a32gsfv-ztzDw$=TLo}=%mwWsn^-i#-VD$x_!1^8-UO$Rk6xnQwQBn~Xd~IuGJwr9;U8Db%N5{wM zjX_@*Ugd|LF3wbUyUdbVLOWz6Y>tyTG2_t2-x0IKgqyPwb5D126=aR>kHRBTg|N4Q zx^k#?tfBnFL6=#{4d-7;O&p617PM%rCW~v^Tq0}Rr0q6*nz%)c0J|YL^1|ml#?TI~ zMt2FJR=p7hV9YS>`{&;?#4rG+ewUc-vCp@Oc=9?YqIlrm?HvsDl}~H~JQWi3&)2Ci)BDKY(M*-KdoojN zpVDUAiv#bAf#eGkBS{B7Vq4qs&SGZ`eB{!x6j0-oFt2T z6!6mzJ;{^8`elm@~)=%U=NHALi~5~DMIWP#PJ`-ta-++{})htW2J3O zkyEt*Bqw74ZoRppc$7t->va~n8lx@!t{>kcK5(y&s7!!xWty$<gLleqEsZxkQyy3GLEgdYfpxKjqwukzNY*dOMsdqWa(CwR!j2Q;~y>56-P=3dx_Q zq6{nT+3<_Zy$X$C&~Z!4;@Yn>KRyY37^waGgZAfnC7OEGQ^$K=U-UA{=e;-W6!K15 z>s0=MP*uBQTZ_0pTG9TT8h=h9ahV*i{gnYsO53LNH`iFdI_u87n_3Bk_LplVxjHAZT6qT9b zI55$g7=A}9w|*b(Hn^$3MgL@dh0$J`Yrf}mPK;zw=HYC}bW@<@H7firm8>nfxH12^ zhi5tCyqbaxkK|s`JeCdGdP$c`yiF+LD24!Q1345y5S?H~izah2 zgE8%y`5YKR%@e!XQ4MFXTY7&c{I(nr2jwrtg?ABvG?FAO=|A z(D85gJFr4(nq~lu-N=@BITe z2$`F%`{ev0W6H0e8hKic`C(uXM_zwFCthbSwWVP~15keZl2|xL8HIR&B&d9ADM*wR z1`&GQMruH@GAm$K3xV0=t-p!tq|@HnKh9hS4+W@VV__MF+C5hD&p>g4V518!5m|`c zFSnFZ|K-}LX32&SO;YcVjLEX1?tQL#pU(H3AwJ}MEJ(d;|I zT#?ixb%$1lOfWO+QFzYZ>qd0v8rf#?A2U z*h1$cb_6QU)>Yy_o*f9msvg?LfS5HY|BopXGWZAgJJk=z|80i{r4Zk?n~o<%SilN3 z@h{Qc$?smyU4hEvPZvx2%Rh18Eo1C^@KSlyc#j|lSKw4UjdpuA)oTrz@DG`(X#ywe z({+zEk()G_0@RSixwZc;XT=V$}h1|t;_2FU`>`gV&_Vk&I;2}b$$PwgQG8x2aU zOC&|}Q=wOkcojYe4Mt7nRqdN_4l^!G({~SUd{#JDTNZFq_DAccJRXuAGIGj}Id zE^StLq@}Ppyk$_ztK6qeW$Sh$y4sR;D%k-y*58hzp1DLZap<95w=DqxM2(`y@aaQW59`FRhLDrC80TC z0wee$jFQqrX>wFsL=#%g+{^K*ucF%xdoDoufQLoZb`yeg>>ONdFr}MaC#tM#JTM*z zkRPgRI@S)!r6<}YEmH)liecx)BmiI#A+tLGE4J0y2ayvCXTPC9_lA*XwYo#}{{ai% B_~ZZp literal 0 HcmV?d00001 diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index 4a0b7b4e0..73509ec61 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -20,7 +20,7 @@ SharpZipLib (#ziplib, formerly NZipLib) is a compression library for Zip, GZip, BZip2, and Tar written entirely in C# for .NET. It is implemented as an assembly (installable in the GAC), and thus can easily be incorporated into other projects (in any .NET language) MIT http://icsharpcode.github.io/SharpZipLib/ - http://icsharpcode.github.io/SharpZipLib/assets/sharpziplib-nuget-256x256.png + images/sharpziplib-nuget-256x256.png https://github.com/icsharpcode/SharpZipLib Copyright © 2000-2020 SharpZipLib Contributors Compression Library Zip GZip BZip2 LZW Tar @@ -33,5 +33,12 @@ Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3 for more + + + + True + images + + From 716b91307de9bc4acd5701e2bc75a4f6360fdb4a Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Thu, 8 Oct 2020 16:29:59 +0100 Subject: [PATCH 057/162] PR #355: Wire up BZip2 compression support for Zip files --- .../Zip/ZipConstants.cs | 5 + src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 8 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 16 +- .../Zip/GeneralHandling.cs | 2 +- .../Zip/ZipFileHandling.cs | 144 ++++++++++++++++++ 5 files changed, 172 insertions(+), 3 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs index cc2fd27d2..b0f33a764 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs @@ -281,6 +281,11 @@ public static class ZipConstants /// public const int VersionZip64 = 45; + /// + /// The version required for BZip2 compression (4.6 or higher) + /// + public const int VersionBZip2 = 46; + #endregion Versions #region Header Sizes diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index d6e4b98fa..3baf8415d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -585,6 +585,10 @@ public int Version { result = 20; } + else if (CompressionMethod.BZip2 == method) + { + result = ZipConstants.VersionBZip2; + } else if (IsDirectory == true) { result = 20; @@ -616,6 +620,7 @@ public bool CanDecompress (Version == 11) || (Version == 20) || (Version == 45) || + (Version == 46) || (Version == 51)) && IsCompressionMethodSupported(); } @@ -1290,7 +1295,8 @@ public static bool IsCompressionMethodSupported(CompressionMethod method) { return (method == CompressionMethod.Deflated) || - (method == CompressionMethod.Stored); + (method == CompressionMethod.Stored) || + (method == CompressionMethod.BZip2); } /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 02fd30778..40fef41b4 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -883,6 +883,10 @@ public Stream GetInputStream(long entryIndex) result = new InflaterInputStream(result, new Inflater(true)); break; + case CompressionMethod.BZip2: + result = new BZip2.BZip2InputStream(result); + break; + default: throw new ZipException("Unsupported compression method " + method); } @@ -1899,7 +1903,7 @@ public void AddDirectory(string directoryName) /// The compression method for the new entry. private void CheckSupportedCompressionMethod(CompressionMethod compressionMethod) { - if (compressionMethod != CompressionMethod.Deflated && compressionMethod != CompressionMethod.Stored) + if (compressionMethod != CompressionMethod.Deflated && compressionMethod != CompressionMethod.Stored && compressionMethod != CompressionMethod.BZip2) { throw new NotImplementedException("Compression method not supported"); } @@ -2636,6 +2640,16 @@ private Stream GetOutputStream(ZipEntry entry) result = dos; break; + case CompressionMethod.BZip2: + var bzos = new BZip2.BZip2OutputStream(result) + { + // If there is an encryption stream in use, then we want that to be disposed when the BZip2OutputStream stream is disposed + // If not, then we don't want it to dispose the base stream + IsStreamOwner = entry.IsCrypted + }; + result = bzos; + break; + default: throw new ZipException("Unknown compression method " + entry.CompressionMethod); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs index b0d22c9bc..b74ed1ddc 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs @@ -141,7 +141,7 @@ public void UnsupportedCompressionMethod() var ze = new ZipEntry("HumblePie"); //ze.CompressionMethod = CompressionMethod.BZip2; - Assert.That(() => ze.CompressionMethod = CompressionMethod.BZip2, + Assert.That(() => ze.CompressionMethod = CompressionMethod.Deflate64, Throws.TypeOf()); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index 7ae234523..4a43211fe 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -1611,5 +1611,149 @@ public void AddFileWithAlternateName() } } } + + /// + /// Test a zip file using BZip2 compression. + /// + [TestCase(true)] + [TestCase(false)] + [Category("Zip")] + public void ZipWithBZip2Compression(bool encryptEntries) + { + string password = "pwd"; + + using (var memStream = new MemoryStream()) + { + using (ZipFile f = new ZipFile(memStream, leaveOpen: true)) + { + if (encryptEntries) + f.Password = password; + + f.BeginUpdate(new MemoryArchiveStorage()); + + var m = new StringMemoryDataSource("BZip2Compressed"); + f.Add(m, "a.dat", CompressionMethod.BZip2); + + var m2 = new StringMemoryDataSource("DeflateCompressed"); + f.Add(m2, "b.dat", CompressionMethod.Deflated); + f.CommitUpdate(); + Assert.IsTrue(f.TestArchive(true)); + } + + memStream.Seek(0, SeekOrigin.Begin); + + using (ZipFile f = new ZipFile(memStream)) + { + if (encryptEntries) + f.Password = password; + + { + var entry = f.GetEntry("a.dat"); + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Compression method should be BZip2"); + Assert.That(entry.Version, Is.EqualTo(ZipConstants.VersionBZip2), "Entry version should be 46"); + Assert.That(entry.IsCrypted, Is.EqualTo(encryptEntries)); + + using (var reader = new StreamReader(f.GetInputStream(entry))) + { + string contents = reader.ReadToEnd(); + Assert.That(contents, Is.EqualTo("BZip2Compressed"), "extract string must match original string"); + } + } + + { + var entry = f.GetEntry("b.dat"); + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.Deflated), "Compression method should be Deflated"); + Assert.That(entry.IsCrypted, Is.EqualTo(encryptEntries)); + + using (var reader = new StreamReader(f.GetInputStream(entry))) + { + string contents = reader.ReadToEnd(); + Assert.That(contents, Is.EqualTo("DeflateCompressed"), "extract string must match original string"); + } + } + } + + // @@TODO@@ verify the archive with 7-zip? + } + } + + /// + /// We should be able to read a bzip2 compressed zip file created by 7-zip. + /// + [Test] + [Category("Zip")] + public void ShouldReadBZip2ZipCreatedBy7Zip() + { + const string BZip2CompressedZipCreatedBy7Zip = + "UEsDBC4AAAAMAIa50U4/rHf5qwAAAK8AAAAJAAAASGVsbG8udHh0QlpoOTFBWSZTWTL8pwYAA" + + "BWfgEhlUAAiLUgQP+feMCAAiCKaeiaBobU9JiaAMGmoak9GmRNqPUDQ9T1PQsz/t9B6YvEdvF" + + "5dhwXzGE1ooO41A6TtATBEFxFUq6trGtUcSJDyWWWj/S2VwY15fy3IqHi3hHUS+K76zdoDzQa" + + "VGE/4YkYZe3JAtv1EsIqIsiTnnktIbBo1R4xY3JZEOm2BvwLuSKcKEgZflODAUEsBAj8ALgAA" + + "AAwAhrnRTj+sd/mrAAAArwAAAAkAJAAAAAAAAAAgAAAAAAAAAEhlbGxvLnR4dAoAIAAAAAAAA" + + "QAYAO97MLZZJdUB73swtlkl1QEK0UTFWCXVAVBLBQYAAAAAAQABAFsAAADSAAAAAAA="; + + const string OriginalText = + "SharpZipLib (#ziplib, formerly NZipLib) is a compression library that supports Zip files using both stored and deflate compression methods, PKZIP 2.0 style and AES encryption."; + + var fileBytes = System.Convert.FromBase64String(BZip2CompressedZipCreatedBy7Zip); + + using (var input = new MemoryStream(fileBytes, false)) + { + using (ZipFile f = new ZipFile(input)) + { + var entry = f.GetEntry("Hello.txt"); + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Compression method should be BZip2"); + Assert.That(entry.Version, Is.EqualTo(ZipConstants.VersionBZip2), "Entry version should be 46"); + + using (var reader = new StreamReader(f.GetInputStream(entry))) + { + string contents = reader.ReadToEnd(); + Assert.That(contents, Is.EqualTo(OriginalText), "extract string must match original string"); + } + } + } + } + + /// + /// We should be able to read a bzip2 compressed / AES encrypted zip file created by 7-zip. + /// + [Test] + [Category("Zip")] + public void ShouldReadAESBZip2ZipCreatedBy7Zip() + { + const string BZip2CompressedZipCreatedBy7Zip = + "UEsDBDMAAQBjAIa50U4AAAAAxwAAAK8AAAAJAAsASGVsbG8udHh0AZkHAAIAQUUDDAAYg6jqf" + + "kvZClVMOtgmqKT0/8I9fMPgo96myxw9hLQUhKj1Qczi3fT7QIhAnAKU+u03nA8rCKGWmDI5Qz" + + "qPREy95boQVDPwmwEsWksv3GAWzMfzZUhmB/TgIJlA34a4yP0f2ucy3/QCQYo8QcHjBtjWX5b" + + "dZn0+fwY9Ci7q8JSI8zNSbgQ0Ert/lIJ9MxQ4lzBxMl4LySkd104cDPh/FslTAcPtHoy8Mf1c" + + "vnI1uICMgjWVeTqYrvSvt2uuHnqr4AiehArFiXTnUEsBAj8AMwABAGMAhrnRTgAAAADHAAAAr" + + "wAAAAkALwAAAAAAAAAgAAAAAAAAAEhlbGxvLnR4dAoAIAAAAAAAAQAYAO97MLZZJdUBYdnjul" + + "kl1QEK0UTFWCXVAQGZBwACAEFFAwwAUEsFBgAAAAABAAEAZgAAAPkAAAAAAA=="; + + const string OriginalText = + "SharpZipLib (#ziplib, formerly NZipLib) is a compression library that supports Zip files using both stored and deflate compression methods, PKZIP 2.0 style and AES encryption."; + + var fileBytes = System.Convert.FromBase64String(BZip2CompressedZipCreatedBy7Zip); + + using (var input = new MemoryStream(fileBytes, false)) + { + using (ZipFile f = new ZipFile(input)) + { + f.Password = "password"; + + var entry = f.GetEntry("Hello.txt"); + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Compression method should be BZip2"); + Assert.That(entry.Version, Is.EqualTo(ZipConstants.VERSION_AES), "Entry version should be 51"); + Assert.That(entry.IsCrypted, Is.True, "Entry should be encrypted"); + Assert.That(entry.AESKeySize, Is.EqualTo(256), "AES Keysize should be 256"); + + using (var reader = new StreamReader(f.GetInputStream(entry))) + { + string contents = reader.ReadToEnd(); + Assert.That(contents, Is.EqualTo(OriginalText), "extract string must match original string"); + } + } + } + } } } From 1e351fceb26f1121f32aac4793e4cec65ae02bcf Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 17 Oct 2020 09:17:02 +0100 Subject: [PATCH 058/162] PR #525: Update the sample projects to use the v1.3 release --- .../cs/Cmd_BZip2/Cmd_BZip2.csproj | 4 ++-- .../cs/Cmd_BZip2/packages.config | 2 +- .../cs/Cmd_Checksum/Cmd_Checksum.csproj | 4 ++-- .../cs/Cmd_Checksum/packages.config | 2 +- .../cs/Cmd_GZip/Cmd_GZip.csproj | 4 ++-- .../cs/Cmd_GZip/packages.config | 2 +- .../ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj | 4 ++-- .../cs/Cmd_Tar/packages.config | 2 +- .../cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj | 4 ++-- .../cs/Cmd_ZipInfo/packages.config | 2 +- .../cs/CreateZipFile/CreateZipFile.csproj | 4 ++-- .../cs/CreateZipFile/packages.config | 2 +- .../cs/FastZip/packages.config | 2 +- samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config | 2 +- samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj | 4 ++-- .../cs/unzipfile/packages.config | 2 +- .../cs/unzipfile/unzipfile.csproj | 4 ++-- .../cs/viewzipfile/packages.config | 2 +- .../cs/viewzipfile/viewzipfile.csproj | 4 ++-- samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config | 2 +- samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj | 4 ++-- .../vb/CreateZipFile/CreateZipFile.vbproj | 4 ++-- .../vb/CreateZipFile/packages.config | 2 +- .../vb/WpfCreateZipFile/WpfCreateZipFile.vbproj | 4 ++-- .../vb/WpfCreateZipFile/packages.config | 2 +- .../vb/minibzip2/minibzip2.vbproj | 4 ++-- .../vb/minibzip2/packages.config | 2 +- .../vb/viewzipfile/packages.config | 2 +- .../vb/viewzipfile/viewzipfile.vbproj | 4 ++-- .../vb/zipfiletest/packages.config | 2 +- .../vb/zipfiletest/zipfiletest.vbproj | 4 ++-- 31 files changed, 46 insertions(+), 46 deletions(-) diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj index b1428fe16..121410932 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj @@ -80,8 +80,8 @@ copy Cmd_BZip2.exe bunzip2.exe 4096 - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj index c47abeba1..7bfc3d9c2 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj @@ -74,8 +74,8 @@ true - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj index 50e9b8d5d..ce1d46a9a 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj @@ -74,8 +74,8 @@ copy Cmd_GZip.exe gunzip.exe true - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj index 7908ee9b8..e002adadf 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj @@ -66,8 +66,8 @@ Cmd_Tar - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj index b2bea17e4..7cb8118c7 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj @@ -73,8 +73,8 @@ true - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj index c6ecc7c43..08cc046ff 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj @@ -81,8 +81,8 @@ - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj index 6348aa8cf..a749293f9 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj @@ -62,8 +62,8 @@ false - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj index 124d295ed..3d8ca89e8 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj @@ -38,8 +38,8 @@ UnZipFileClass - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj index b77719bfe..531d502c4 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj @@ -38,8 +38,8 @@ ViewZipFileClass - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj index 433998e69..9013296b9 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj @@ -62,8 +62,8 @@ false - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj index 0188f762b..c20cdae13 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj @@ -66,8 +66,8 @@ false - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj index 2bbcc5e51..5d882b23d 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj @@ -73,8 +73,8 @@ My Project\app.manifest - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config index a01e717c5..1380bfc2b 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config @@ -1,5 +1,5 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj index e2a950a84..9c2dfd7e2 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj @@ -74,8 +74,8 @@ My Project\app.manifest - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj index c47e0be6f..a7e5259e5 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj @@ -66,8 +66,8 @@ false - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config index 0eb486c15..a938c1f99 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj index ebd109ddb..4a53b5a64 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj @@ -76,8 +76,8 @@ 42353,42354,42355 - - ..\..\packages\SharpZipLib.1.2.0\lib\net45\ICSharpCode.SharpZipLib.dll + + ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll From 91050e623f481912f8fbcbb31a7bd9faff2e03c9 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 17 Oct 2020 09:19:58 +0100 Subject: [PATCH 059/162] PR #511: Move the 7zip helper functions into their own class for easier reuse --- .../TestSupport/SevenZip.cs | 99 +++++++++++++++++ .../Zip/ZipEncryptionHandling.cs | 101 +----------------- 2 files changed, 104 insertions(+), 96 deletions(-) create mode 100644 test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs new file mode 100644 index 000000000..c312ec401 --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs @@ -0,0 +1,99 @@ +using System; +using System.Diagnostics; +using System.IO; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.TestSupport +{ + // Helper class for verifying zips with 7-zip + internal static class SevenZipHelper + { + private static readonly string[] possible7zPaths = new[] { + // Check in PATH + "7z", "7za", + + // Check in default install location + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "7-Zip", "7z.exe"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "7-Zip", "7z.exe"), + }; + + public static bool TryGet7zBinPath(out string path7z) + { + var runTimeLimit = TimeSpan.FromSeconds(3); + + foreach (var testPath in possible7zPaths) + { + try + { + var p = Process.Start(new ProcessStartInfo(testPath, "i") + { + RedirectStandardOutput = true, + UseShellExecute = false + }); + while (!p.StandardOutput.EndOfStream && (DateTime.Now - p.StartTime) < runTimeLimit) + { + p.StandardOutput.DiscardBufferedData(); + } + if (!p.HasExited) + { + p.Close(); + Assert.Warn($"Timed out checking for 7z binary in \"{testPath}\"!"); + continue; + } + + if (p.ExitCode == 0) + { + path7z = testPath; + return true; + } + } + catch (Exception) + { + continue; + } + } + path7z = null; + return false; + } + + /// + /// Helper function to verify the provided zip stream with 7Zip. + /// + /// A stream containing the zip archive to test. + /// The password for the archive. + internal static void VerifyZipWith7Zip(Stream zipStream, string password) + { + if (TryGet7zBinPath(out string path7z)) + { + Console.WriteLine($"Using 7z path: \"{path7z}\""); + + var fileName = Path.GetTempFileName(); + + try + { + using (var fs = File.OpenWrite(fileName)) + { + zipStream.Seek(0, SeekOrigin.Begin); + zipStream.CopyTo(fs); + } + + var p = Process.Start(path7z, $"t -p{password} \"{fileName}\""); + if (!p.WaitForExit(2000)) + { + Assert.Warn("Timed out verifying zip file!"); + } + + Assert.AreEqual(0, p.ExitCode, "Archive verification failed"); + } + finally + { + File.Delete(fileName); + } + } + else + { + Assert.Warn("Skipping file verification since 7za is not in path"); + } + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index 49317207c..34dde202b 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -1,8 +1,6 @@ -using ICSharpCode.SharpZipLib.Core; -using ICSharpCode.SharpZipLib.Zip; +using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; using System; -using System.Diagnostics; using System.IO; using System.Text; using ICSharpCode.SharpZipLib.Tests.TestSupport; @@ -74,7 +72,7 @@ public void ZipOutputStreamEncryptEmptyEntries( zipOutputStream.CloseEntry(); } - VerifyZipWith7Zip(ms, "password"); + SevenZipHelper.VerifyZipWith7Zip(ms, "password"); } } @@ -315,7 +313,7 @@ public void ZipFileAesAdd() } // As an extra test, verify the file with 7-zip - VerifyZipWith7Zip(memoryStream, password); + SevenZipHelper.VerifyZipWith7Zip(memoryStream, password); } } @@ -399,7 +397,7 @@ public void ZipFileAesDelete() } // As an extra test, verify the file with 7-zip - VerifyZipWith7Zip(memoryStream, password); + SevenZipHelper.VerifyZipWith7Zip(memoryStream, password); } } @@ -471,54 +469,6 @@ public void ZipinputStreamShouldGracefullyFailWithAESStreams() } } - private static readonly string[] possible7zPaths = new[] { - // Check in PATH - "7z", "7za", - - // Check in default install location - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "7-Zip", "7z.exe"), - Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "7-Zip", "7z.exe"), - }; - - public static bool TryGet7zBinPath(out string path7z) - { - var runTimeLimit = TimeSpan.FromSeconds(3); - - foreach (var testPath in possible7zPaths) - { - try - { - var p = Process.Start(new ProcessStartInfo(testPath, "i") - { - RedirectStandardOutput = true, - UseShellExecute = false - }); - while (!p.StandardOutput.EndOfStream && (DateTime.Now - p.StartTime) < runTimeLimit) - { - p.StandardOutput.DiscardBufferedData(); - } - if (!p.HasExited) - { - p.Close(); - Assert.Warn($"Timed out checking for 7z binary in \"{testPath}\"!"); - continue; - } - - if (p.ExitCode == 0) - { - path7z = testPath; - return true; - } - } - catch (Exception) - { - continue; - } - } - path7z = null; - return false; - } - public void WriteEncryptedZipToStream(Stream stream, string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated) { using (var zs = new ZipOutputStream(stream)) @@ -572,51 +522,10 @@ public void CreateZipWithEncryptedEntries(string password, int keySize, Compress using (var ms = new MemoryStream()) { WriteEncryptedZipToStream(ms, password, keySize, compressionMethod); - VerifyZipWith7Zip(ms, password); - } - } - - /// - /// Helper function to verify the provided zip stream with 7Zip. - /// - /// A stream containing the zip archive to test. - /// The password for the archive. - private void VerifyZipWith7Zip(Stream zipStream, string password) - { - if (TryGet7zBinPath(out string path7z)) - { - Console.WriteLine($"Using 7z path: \"{path7z}\""); - - var fileName = Path.GetTempFileName(); - - try - { - using (var fs = File.OpenWrite(fileName)) - { - zipStream.Seek(0, SeekOrigin.Begin); - zipStream.CopyTo(fs); - } - - var p = Process.Start(path7z, $"t -p{password} \"{fileName}\""); - if (!p.WaitForExit(2000)) - { - Assert.Warn("Timed out verifying zip file!"); - } - - Assert.AreEqual(0, p.ExitCode, "Archive verification failed"); - } - finally - { - File.Delete(fileName); - } - } - else - { - Assert.Warn("Skipping file verification since 7za is not in path"); + SevenZipHelper.VerifyZipWith7Zip(ms, password); } } - private const string DummyDataString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce bibendum diam ac nunc rutrum ornare. Maecenas blandit elit ligula, eget suscipit lectus rutrum eu. Maecenas aliquam, purus mattis pulvinar pharetra, nunc orci maximus justo, sed facilisis massa dui sed lorem. From 9e027502d1aaca863d9035deac1ec320c0e6f31f Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 17 Oct 2020 09:24:41 +0100 Subject: [PATCH 060/162] PR #509: Make PutNextEntry throw if the entry is AES and no password has been set refs #507 --- .../Zip/ZipOutputStream.cs | 6 ++++++ .../Zip/StreamHandling.cs | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 1bd544c2d..dd752eb3c 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -262,6 +262,12 @@ public void PutNextEntry(ZipEntry entry) throw new NotImplementedException("Compression method not supported"); } + // A password must have been set in order to add AES encrypted entries + if (entry.AESKeySize > 0 && string.IsNullOrEmpty(this.Password)) + { + throw new InvalidOperationException("The Password property must be set before AES encrypted entries can be added"); + } + int compressionLevel = defaultCompressionLevel; // Clear flags that the library manages internally diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index cb2c72d16..60d7a5709 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -502,5 +502,23 @@ public void ShouldBeAbleToReadEntriesWithInvalidFileNames() } } } + + /// + /// Test for https://github.com/icsharpcode/SharpZipLib/issues/507 + /// + [Test] + [Category("Zip")] + public void AddingAnAESEntryWithNoPasswordShouldThrow() + { + using (var memoryStream = new MemoryStream()) + { + using (var outStream = new ZipOutputStream(memoryStream)) + { + var newEntry = new ZipEntry("test") { AESKeySize = 256 }; + + Assert.Throws(() => outStream.PutNextEntry(newEntry)); + } + } + } } } From ad026884e8037f87b5b78170f6056b75911506f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Mon, 19 Oct 2020 12:04:12 +0200 Subject: [PATCH 061/162] #PR 529: Add release workflow --- .github/workflows/release.yml | 43 +++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .github/workflows/release.yml diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..e5cf14563 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,43 @@ +# Workflow to execute when a new version is released +name: Release + +on: + release: + + # Used for testing and manual execution + workflow_dispatch: + inputs: + tag: + description: 'Tag Ref' + required: true + +jobs: + docfx: + runs-on: ubuntu-latest + name: Update DocFX documentation + steps: + - uses: actions/checkout@v2 + with: + ref: ${{ github.events.inputs.tag }} + - uses: nikeee/docfx-action@v1.0.0 + name: Build Documentation + with: + args: docs/help/docfx.json + +# Disabled until know to be working +# - uses: JamesIves/github-pages-deploy-action@3.6.2 +# name: Publish documentation to Github Pages +# with: +# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +# BRANCH: gh-pages +# +# # The folder the action should deploy. +# FOLDER: _site +# +# # Automatically remove deleted files from the deploy branch +# CLEAN: true + + - name: Upload documentation as artifact + uses: actions/upload-artifact@v2 + with: + path: _site From d0efee019d5c1b21f8c6957cb6742d28fc60eef7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Mon, 19 Oct 2020 13:12:54 +0200 Subject: [PATCH 062/162] PR #530: Fix Codacy Workflows Updates the Codacy Action to v1.1.0 --- .github/workflows/on-push.yml | 2 +- .github/workflows/pull-request.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index cb5c48119..6b09c2b4d 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -51,7 +51,7 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - name: Run codacy-analysis-cli - uses: codacy/codacy-analysis-cli-action@1.0.1 + uses: codacy/codacy-analysis-cli-action@1.1.0 with: # The current issues needs to be fixed before this can be removed max-allowed-issues: 9999 diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 1637f4579..aedb7fc5e 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -69,7 +69,7 @@ jobs: - name: Checkout code uses: actions/checkout@v2 - name: Run codacy-analysis-cli - uses: codacy/codacy-analysis-cli-action@1.0.1 + uses: codacy/codacy-analysis-cli-action@1.1.0 with: # The current issues needs to be fixed before this can be removed max-allowed-issues: 9999 From 134b8f4055d60cc02b3c405dd9c936d6bb5514b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 21 Nov 2020 12:30:07 +0100 Subject: [PATCH 063/162] PR #539: Use securely generated random temporary file names - Use GetRandomFileName() instead of GetTempFileName() - Unify random file name creation into PathUtils - Do not create new random files before use - Rename WindowsPathUtils to PathUtils and make a proper static class --- .../{WindowsPathUtils.cs => PathUtils.cs} | 35 +++++++--- .../Zip/WindowsNameTransform.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 66 ++----------------- .../Zip/ZipNameTransform.cs | 4 +- 4 files changed, 32 insertions(+), 75 deletions(-) rename src/ICSharpCode.SharpZipLib/Core/{WindowsPathUtils.cs => PathUtils.cs} (64%) diff --git a/src/ICSharpCode.SharpZipLib/Core/WindowsPathUtils.cs b/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs similarity index 64% rename from src/ICSharpCode.SharpZipLib/Core/WindowsPathUtils.cs rename to src/ICSharpCode.SharpZipLib/Core/PathUtils.cs index f02a0affb..2d6121786 100644 --- a/src/ICSharpCode.SharpZipLib/Core/WindowsPathUtils.cs +++ b/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs @@ -1,23 +1,18 @@ +using System.IO; + namespace ICSharpCode.SharpZipLib.Core { /// - /// WindowsPathUtils provides simple utilities for handling windows paths. + /// PathUtils provides simple utilities for handling paths. /// - public abstract class WindowsPathUtils + public static class PathUtils { - /// - /// Initializes a new instance of the class. - /// - internal WindowsPathUtils() - { - } - /// /// Remove any path root present in the path /// /// A containing path information. /// The path with the root removed if it was present; path otherwise. - /// Unlike the class the path isnt otherwise checked for validity. + /// Unlike the class the path isn't otherwise checked for validity. public static string DropPathRoot(string path) { string result = path; @@ -63,5 +58,25 @@ public static string DropPathRoot(string path) } return result; } + + /// + /// Returns a random file name in the users temporary directory, or in directory of if specified + /// + /// If specified, used as the base file name for the temporary file + /// Returns a temporary file name + public static string GetTempFileName(string original) + { + string fileName; + var tempPath = Path.GetTempPath(); + + do + { + fileName = original == null + ? Path.Combine(tempPath, Path.GetRandomFileName()) + : $"{original}.{Path.GetRandomFileName()}"; + } while (File.Exists(fileName)); + + return fileName; + } } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs b/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs index c10f5ceab..0572cec08 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs @@ -176,7 +176,7 @@ public static string MakeValidName(string name, char replacement) throw new ArgumentNullException(nameof(name)); } - name = WindowsPathUtils.DropPathRoot(name.Replace("/", Path.DirectorySeparatorChar.ToString())); + name = PathUtils.DropPathRoot(name.Replace("/", Path.DirectorySeparatorChar.ToString())); // Drop any leading slashes. while ((name.Length > 0) && (name[0] == Path.DirectorySeparatorChar)) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 40fef41b4..ffe55cd8b 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -4622,18 +4622,8 @@ public DiskArchiveStorage(ZipFile file) /// Returns the temporary output stream. public override Stream GetTemporaryOutput() { - if (temporaryName_ != null) - { - temporaryName_ = GetTempFileName(temporaryName_, true); - temporaryStream_ = File.Open(temporaryName_, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); - } - else - { - // Determine where to place files based on internal strategy. - // Currently this is always done in system temp directory. - temporaryName_ = Path.GetTempFileName(); - temporaryStream_ = File.Open(temporaryName_, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); - } + temporaryName_ = PathUtils.GetTempFileName(temporaryName_); + temporaryStream_ = File.Open(temporaryName_, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); return temporaryStream_; } @@ -4652,7 +4642,7 @@ public override Stream ConvertTemporaryToFinal() Stream result = null; - string moveTempName = GetTempFileName(fileName_, false); + string moveTempName = PathUtils.GetTempFileName(fileName_); bool newFileCreated = false; try @@ -4691,7 +4681,7 @@ public override Stream MakeTemporaryCopy(Stream stream) { stream.Dispose(); - temporaryName_ = GetTempFileName(fileName_, true); + temporaryName_ = PathUtils.GetTempFileName(fileName_); File.Copy(fileName_, temporaryName_, true); temporaryStream_ = new FileStream(temporaryName_, @@ -4741,54 +4731,6 @@ public override void Dispose() #endregion IArchiveStorage Members - #region Internal routines - - private static string GetTempFileName(string original, bool makeTempFile) - { - string result = null; - - if (original == null) - { - result = Path.GetTempFileName(); - } - else - { - int counter = 0; - int suffixSeed = DateTime.Now.Second; - - while (result == null) - { - counter += 1; - string newName = string.Format("{0}.{1}{2}.tmp", original, suffixSeed, counter); - if (!File.Exists(newName)) - { - if (makeTempFile) - { - try - { - // Try and create the file. - using (FileStream stream = File.Create(newName)) - { - } - result = newName; - } - catch - { - suffixSeed = DateTime.Now.Second; - } - } - else - { - result = newName; - } - } - } - } - return result; - } - - #endregion Internal routines - #region Instance Fields private Stream temporaryStream_; diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs index 2c0591671..f91b20c3d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipNameTransform.cs @@ -93,7 +93,7 @@ public string TransformFile(string name) } name = name.Replace(@"\", "/"); - name = WindowsPathUtils.DropPathRoot(name); + name = PathUtils.DropPathRoot(name); // Drop any leading and trailing slashes. name = name.Trim('/'); @@ -289,7 +289,7 @@ public string TransformFile(string name) name = name.Replace(@"\", "/"); // Remove the path root. - name = WindowsPathUtils.DropPathRoot(name); + name = PathUtils.DropPathRoot(name); // Drop any leading and trailing slashes. name = name.Trim('/'); From 7520a3ff663377102bdfc9f586f22af82661b9a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 21 Nov 2020 12:33:16 +0100 Subject: [PATCH 064/162] PR #538: Use RNGCryptoServiceProvider for crypto headers - Use RNGCryptoServiceProvider for crypto headers - Dispose RNG service after use in ZipCrypto --- src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs | 6 ++++-- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 6 ++++-- src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs | 8 ++++++-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs b/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs index 7a8c55e6e..6730c9dee 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs @@ -444,8 +444,10 @@ public override byte[] Key public override void GenerateKey() { key_ = new byte[12]; - var rnd = new Random(); - rnd.NextBytes(key_); + using (var rng = new RNGCryptoServiceProvider()) + { + rng.GetBytes(key_); + } } /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index ffe55cd8b..bce0b609f 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -3727,8 +3727,10 @@ private static void CheckClassicPassword(CryptoStream classicCryptoStream, ZipEn private static void WriteEncryptionHeader(Stream stream, long crcValue) { byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; - var rnd = new Random(); - rnd.NextBytes(cryptBuffer); + using (var rng = new RNGCryptoServiceProvider()) + { + rng.GetBytes(cryptBuffer); + } cryptBuffer[11] = (byte)(crcValue >> 24); stream.Write(cryptBuffer, 0, cryptBuffer.Length); } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index dd752eb3c..b9131d040 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Security.Cryptography; namespace ICSharpCode.SharpZipLib.Zip { @@ -633,8 +634,11 @@ private void WriteEncryptionHeader(long crcValue) InitializePassword(Password); byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; - var rnd = new Random(); - rnd.NextBytes(cryptBuffer); + using (var rng = new RNGCryptoServiceProvider()) + { + rng.GetBytes(cryptBuffer); + } + cryptBuffer[11] = (byte)(crcValue >> 24); EncryptBlock(cryptBuffer, 0, cryptBuffer.Length); From ddc545bd6f3a9ab317705f1706f55dee41bd24c3 Mon Sep 17 00:00:00 2001 From: Nelson Gomez Date: Sat, 21 Nov 2020 03:44:17 -0800 Subject: [PATCH 065/162] PR #516: Improve CRC32 performance --- .../Checksum/BZip2Crc.cs | 132 +++++++-------- src/ICSharpCode.SharpZipLib/Checksum/Crc32.cs | 121 +++++++------- .../Checksum/CrcUtilities.cs | 158 ++++++++++++++++++ .../Checksum/ChecksumTests.cs | 60 +++++++ 4 files changed, 335 insertions(+), 136 deletions(-) create mode 100644 src/ICSharpCode.SharpZipLib/Checksum/CrcUtilities.cs diff --git a/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs b/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs index 16cfda05b..be76da11e 100644 --- a/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs +++ b/src/ICSharpCode.SharpZipLib/Checksum/BZip2Crc.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.CompilerServices; namespace ICSharpCode.SharpZipLib.Checksum { @@ -25,9 +26,19 @@ namespace ICSharpCode.SharpZipLib.Checksum /// out is a one). We start with the highest power (least significant bit) of /// q and repeat for all eight bits of q. /// - /// The table is simply the CRC of all possible eight bit values. This is all - /// the information needed to generate CRC's on data a byte at a time for all - /// combinations of CRC register values and incoming bytes. + /// This implementation uses sixteen lookup tables stored in one linear array + /// to implement the slicing-by-16 algorithm, a variant of the slicing-by-8 + /// algorithm described in this Intel white paper: + /// + /// https://web.archive.org/web/20120722193753/http://download.intel.com/technology/comms/perfnet/download/slicing-by-8.pdf + /// + /// The first lookup table is simply the CRC of all possible eight bit values. + /// Each successive lookup table is derived from the original table generated + /// by Sarwate's algorithm. Slicing a 16-bit input and XORing the outputs + /// together will produce the same output as a byte-by-byte CRC loop with + /// fewer arithmetic and bit manipulation operations, at the cost of increased + /// memory consumed by the lookup tables. (Slicing-by-16 requires a 16KB table, + /// which is still small enough to fit in most processors' L1 cache.) /// public sealed class BZip2Crc : IChecksum { @@ -36,72 +47,7 @@ public sealed class BZip2Crc : IChecksum private const uint crcInit = 0xFFFFFFFF; //const uint crcXor = 0x00000000; - private static readonly uint[] crcTable = { - 0X00000000, 0X04C11DB7, 0X09823B6E, 0X0D4326D9, - 0X130476DC, 0X17C56B6B, 0X1A864DB2, 0X1E475005, - 0X2608EDB8, 0X22C9F00F, 0X2F8AD6D6, 0X2B4BCB61, - 0X350C9B64, 0X31CD86D3, 0X3C8EA00A, 0X384FBDBD, - 0X4C11DB70, 0X48D0C6C7, 0X4593E01E, 0X4152FDA9, - 0X5F15ADAC, 0X5BD4B01B, 0X569796C2, 0X52568B75, - 0X6A1936C8, 0X6ED82B7F, 0X639B0DA6, 0X675A1011, - 0X791D4014, 0X7DDC5DA3, 0X709F7B7A, 0X745E66CD, - 0X9823B6E0, 0X9CE2AB57, 0X91A18D8E, 0X95609039, - 0X8B27C03C, 0X8FE6DD8B, 0X82A5FB52, 0X8664E6E5, - 0XBE2B5B58, 0XBAEA46EF, 0XB7A96036, 0XB3687D81, - 0XAD2F2D84, 0XA9EE3033, 0XA4AD16EA, 0XA06C0B5D, - 0XD4326D90, 0XD0F37027, 0XDDB056FE, 0XD9714B49, - 0XC7361B4C, 0XC3F706FB, 0XCEB42022, 0XCA753D95, - 0XF23A8028, 0XF6FB9D9F, 0XFBB8BB46, 0XFF79A6F1, - 0XE13EF6F4, 0XE5FFEB43, 0XE8BCCD9A, 0XEC7DD02D, - 0X34867077, 0X30476DC0, 0X3D044B19, 0X39C556AE, - 0X278206AB, 0X23431B1C, 0X2E003DC5, 0X2AC12072, - 0X128E9DCF, 0X164F8078, 0X1B0CA6A1, 0X1FCDBB16, - 0X018AEB13, 0X054BF6A4, 0X0808D07D, 0X0CC9CDCA, - 0X7897AB07, 0X7C56B6B0, 0X71159069, 0X75D48DDE, - 0X6B93DDDB, 0X6F52C06C, 0X6211E6B5, 0X66D0FB02, - 0X5E9F46BF, 0X5A5E5B08, 0X571D7DD1, 0X53DC6066, - 0X4D9B3063, 0X495A2DD4, 0X44190B0D, 0X40D816BA, - 0XACA5C697, 0XA864DB20, 0XA527FDF9, 0XA1E6E04E, - 0XBFA1B04B, 0XBB60ADFC, 0XB6238B25, 0XB2E29692, - 0X8AAD2B2F, 0X8E6C3698, 0X832F1041, 0X87EE0DF6, - 0X99A95DF3, 0X9D684044, 0X902B669D, 0X94EA7B2A, - 0XE0B41DE7, 0XE4750050, 0XE9362689, 0XEDF73B3E, - 0XF3B06B3B, 0XF771768C, 0XFA325055, 0XFEF34DE2, - 0XC6BCF05F, 0XC27DEDE8, 0XCF3ECB31, 0XCBFFD686, - 0XD5B88683, 0XD1799B34, 0XDC3ABDED, 0XD8FBA05A, - 0X690CE0EE, 0X6DCDFD59, 0X608EDB80, 0X644FC637, - 0X7A089632, 0X7EC98B85, 0X738AAD5C, 0X774BB0EB, - 0X4F040D56, 0X4BC510E1, 0X46863638, 0X42472B8F, - 0X5C007B8A, 0X58C1663D, 0X558240E4, 0X51435D53, - 0X251D3B9E, 0X21DC2629, 0X2C9F00F0, 0X285E1D47, - 0X36194D42, 0X32D850F5, 0X3F9B762C, 0X3B5A6B9B, - 0X0315D626, 0X07D4CB91, 0X0A97ED48, 0X0E56F0FF, - 0X1011A0FA, 0X14D0BD4D, 0X19939B94, 0X1D528623, - 0XF12F560E, 0XF5EE4BB9, 0XF8AD6D60, 0XFC6C70D7, - 0XE22B20D2, 0XE6EA3D65, 0XEBA91BBC, 0XEF68060B, - 0XD727BBB6, 0XD3E6A601, 0XDEA580D8, 0XDA649D6F, - 0XC423CD6A, 0XC0E2D0DD, 0XCDA1F604, 0XC960EBB3, - 0XBD3E8D7E, 0XB9FF90C9, 0XB4BCB610, 0XB07DABA7, - 0XAE3AFBA2, 0XAAFBE615, 0XA7B8C0CC, 0XA379DD7B, - 0X9B3660C6, 0X9FF77D71, 0X92B45BA8, 0X9675461F, - 0X8832161A, 0X8CF30BAD, 0X81B02D74, 0X857130C3, - 0X5D8A9099, 0X594B8D2E, 0X5408ABF7, 0X50C9B640, - 0X4E8EE645, 0X4A4FFBF2, 0X470CDD2B, 0X43CDC09C, - 0X7B827D21, 0X7F436096, 0X7200464F, 0X76C15BF8, - 0X68860BFD, 0X6C47164A, 0X61043093, 0X65C52D24, - 0X119B4BE9, 0X155A565E, 0X18197087, 0X1CD86D30, - 0X029F3D35, 0X065E2082, 0X0B1D065B, 0X0FDC1BEC, - 0X3793A651, 0X3352BBE6, 0X3E119D3F, 0X3AD08088, - 0X2497D08D, 0X2056CD3A, 0X2D15EBE3, 0X29D4F654, - 0XC5A92679, 0XC1683BCE, 0XCC2B1D17, 0XC8EA00A0, - 0XD6AD50A5, 0XD26C4D12, 0XDF2F6BCB, 0XDBEE767C, - 0XE3A1CBC1, 0XE760D676, 0XEA23F0AF, 0XEEE2ED18, - 0XF0A5BD1D, 0XF464A0AA, 0XF9278673, 0XFDE69BC4, - 0X89B8FD09, 0X8D79E0BE, 0X803AC667, 0X84FBDBD0, - 0X9ABC8BD5, 0X9E7D9662, 0X933EB0BB, 0X97FFAD0C, - 0XAFB010B1, 0XAB710D06, 0XA6322BDF, 0XA2F33668, - 0XBCB4666D, 0XB8757BDA, 0XB5365D03, 0XB1F740B4 - }; + private static readonly uint[] crcTable = CrcUtilities.GenerateSlicingLookupTable(0x04C11DB7, isReversed: false); /// /// The CRC data checksum so far. @@ -149,6 +95,7 @@ public long Value /// the byte is taken as the lower 8 bits of bval /// /// Reversed Data = false + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Update(int bval) { checkValue = unchecked(crcTable[(byte)(((checkValue >> 24) & 0xFF) ^ bval)] ^ (checkValue << 8)); @@ -166,7 +113,7 @@ public void Update(byte[] buffer) throw new ArgumentNullException(nameof(buffer)); } - Update(new ArraySegment(buffer, 0, buffer.Length)); + Update(buffer, 0, buffer.Length); } /// @@ -177,11 +124,48 @@ public void Update(byte[] buffer) /// public void Update(ArraySegment segment) { - var count = segment.Count; - var offset = segment.Offset; + Update(segment.Array, segment.Offset, segment.Count); + } + + /// + /// Internal helper function for updating a block of data using slicing. + /// + /// The array containing the data to add + /// Range start for (inclusive) + /// The number of bytes to checksum starting from + private void Update(byte[] data, int offset, int count) + { + int remainder = count % CrcUtilities.SlicingDegree; + int end = offset + count - remainder; + + while (offset != end) + { + checkValue = CrcUtilities.UpdateDataForNormalPoly(data, offset, crcTable, checkValue); + offset += CrcUtilities.SlicingDegree; + } - while (--count >= 0) - Update(segment.Array[offset++]); + if (remainder != 0) + { + SlowUpdateLoop(data, offset, end + remainder); + } + } + + /// + /// A non-inlined function for updating data that doesn't fit in a 16-byte + /// block. We don't expect to enter this function most of the time, and when + /// we do we're not here for long, so disabling inlining here improves + /// performance overall. + /// + /// The array containing the data to add + /// Range start for (inclusive) + /// Range end for (exclusive) + [MethodImpl(MethodImplOptions.NoInlining)] + private void SlowUpdateLoop(byte[] data, int offset, int end) + { + while (offset != end) + { + Update(data[offset++]); + } } } } diff --git a/src/ICSharpCode.SharpZipLib/Checksum/Crc32.cs b/src/ICSharpCode.SharpZipLib/Checksum/Crc32.cs index 9b8ab4b6d..740aff566 100644 --- a/src/ICSharpCode.SharpZipLib/Checksum/Crc32.cs +++ b/src/ICSharpCode.SharpZipLib/Checksum/Crc32.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.CompilerServices; namespace ICSharpCode.SharpZipLib.Checksum { @@ -25,9 +26,19 @@ namespace ICSharpCode.SharpZipLib.Checksum /// out is a one). We start with the highest power (least significant bit) of /// q and repeat for all eight bits of q. /// - /// The table is simply the CRC of all possible eight bit values. This is all - /// the information needed to generate CRC's on data a byte at a time for all - /// combinations of CRC register values and incoming bytes. + /// This implementation uses sixteen lookup tables stored in one linear array + /// to implement the slicing-by-16 algorithm, a variant of the slicing-by-8 + /// algorithm described in this Intel white paper: + /// + /// https://web.archive.org/web/20120722193753/http://download.intel.com/technology/comms/perfnet/download/slicing-by-8.pdf + /// + /// The first lookup table is simply the CRC of all possible eight bit values. + /// Each successive lookup table is derived from the original table generated + /// by Sarwate's algorithm. Slicing a 16-bit input and XORing the outputs + /// together will produce the same output as a byte-by-byte CRC loop with + /// fewer arithmetic and bit manipulation operations, at the cost of increased + /// memory consumed by the lookup tables. (Slicing-by-16 requires a 16KB table, + /// which is still small enough to fit in most processors' L1 cache.) /// public sealed class Crc32 : IChecksum { @@ -36,60 +47,7 @@ public sealed class Crc32 : IChecksum private static readonly uint crcInit = 0xFFFFFFFF; private static readonly uint crcXor = 0xFFFFFFFF; - private static readonly uint[] crcTable = { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, - 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, - 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, - 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, - 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, - 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, - 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, - 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, - 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, - 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, - 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, - 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, - 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, - 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, - 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, - 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, - 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, - 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, - 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, - 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, - 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, - 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, - 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, - 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, - 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, - 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, - 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, - 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, - 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, - 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, - 0x2D02EF8D - }; + private static readonly uint[] crcTable = CrcUtilities.GenerateSlicingLookupTable(0xEDB88320, isReversed: true); /// /// The CRC data checksum so far. @@ -98,6 +56,7 @@ public sealed class Crc32 : IChecksum #endregion Instance Fields + [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ComputeCrc32(uint oldCrc, byte bval) { return (uint)(Crc32.crcTable[(oldCrc ^ bval) & 0xFF] ^ (oldCrc >> 8)); @@ -138,6 +97,7 @@ public long Value /// the byte is taken as the lower 8 bits of bval /// /// Reversed Data = true + [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Update(int bval) { checkValue = unchecked(crcTable[(checkValue ^ bval) & 0xFF] ^ (checkValue >> 8)); @@ -155,7 +115,7 @@ public void Update(byte[] buffer) throw new ArgumentNullException(nameof(buffer)); } - Update(new ArraySegment(buffer, 0, buffer.Length)); + Update(buffer, 0, buffer.Length); } /// @@ -166,11 +126,48 @@ public void Update(byte[] buffer) /// public void Update(ArraySegment segment) { - var count = segment.Count; - var offset = segment.Offset; + Update(segment.Array, segment.Offset, segment.Count); + } + + /// + /// Internal helper function for updating a block of data using slicing. + /// + /// The array containing the data to add + /// Range start for (inclusive) + /// The number of bytes to checksum starting from + private void Update(byte[] data, int offset, int count) + { + int remainder = count % CrcUtilities.SlicingDegree; + int end = offset + count - remainder; + + while (offset != end) + { + checkValue = CrcUtilities.UpdateDataForReversedPoly(data, offset, crcTable, checkValue); + offset += CrcUtilities.SlicingDegree; + } - while (--count >= 0) - Update(segment.Array[offset++]); + if (remainder != 0) + { + SlowUpdateLoop(data, offset, end + remainder); + } + } + + /// + /// A non-inlined function for updating data that doesn't fit in a 16-byte + /// block. We don't expect to enter this function most of the time, and when + /// we do we're not here for long, so disabling inlining here improves + /// performance overall. + /// + /// The array containing the data to add + /// Range start for (inclusive) + /// Range end for (exclusive) + [MethodImpl(MethodImplOptions.NoInlining)] + private void SlowUpdateLoop(byte[] data, int offset, int end) + { + while (offset != end) + { + Update(data[offset++]); + } } } } diff --git a/src/ICSharpCode.SharpZipLib/Checksum/CrcUtilities.cs b/src/ICSharpCode.SharpZipLib/Checksum/CrcUtilities.cs new file mode 100644 index 000000000..575abe08b --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Checksum/CrcUtilities.cs @@ -0,0 +1,158 @@ +using System.Runtime.CompilerServices; + +namespace ICSharpCode.SharpZipLib.Checksum +{ + internal static class CrcUtilities + { + /// + /// The number of slicing lookup tables to generate. + /// + internal const int SlicingDegree = 16; + + /// + /// Generates multiple CRC lookup tables for a given polynomial, stored + /// in a linear array of uints. The first block (i.e. the first 256 + /// elements) is the same as the byte-by-byte CRC lookup table. + /// + /// The generating CRC polynomial + /// Whether the polynomial is in reversed bit order + /// A linear array of 256 * elements + /// + /// This table could also be generated as a rectangular array, but the + /// JIT compiler generates slower code than if we use a linear array. + /// Known issue, see: https://github.com/dotnet/runtime/issues/30275 + /// + internal static uint[] GenerateSlicingLookupTable(uint polynomial, bool isReversed) + { + var table = new uint[256 * SlicingDegree]; + uint one = isReversed ? 1 : (1U << 31); + + for (int i = 0; i < 256; i++) + { + uint res = (uint)(isReversed ? i : i << 24); + for (int j = 0; j < SlicingDegree; j++) + { + for (int k = 0; k < 8; k++) + { + if (isReversed) + { + res = (res & one) == 1 ? polynomial ^ (res >> 1) : res >> 1; + } + else + { + res = (res & one) != 0 ? polynomial ^ (res << 1) : res << 1; + } + } + + table[(256 * j) + i] = res; + } + } + + return table; + } + + /// + /// Mixes the first four bytes of input with + /// using normal ordering before calling . + /// + /// Array of data to checksum + /// Offset to start reading from + /// The table to use for slicing-by-16 lookup + /// Checksum state before this update call + /// A new unfinalized checksum value + /// + /// + /// Assumes input[offset]..input[offset + 15] are valid array indexes. + /// For performance reasons, this must be checked by the caller. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static uint UpdateDataForNormalPoly(byte[] input, int offset, uint[] crcTable, uint checkValue) + { + byte x1 = (byte)((byte)(checkValue >> 24) ^ input[offset]); + byte x2 = (byte)((byte)(checkValue >> 16) ^ input[offset + 1]); + byte x3 = (byte)((byte)(checkValue >> 8) ^ input[offset + 2]); + byte x4 = (byte)((byte)checkValue ^ input[offset + 3]); + + return UpdateDataCommon(input, offset, crcTable, x1, x2, x3, x4); + } + + /// + /// Mixes the first four bytes of input with + /// using reflected ordering before calling . + /// + /// Array of data to checksum + /// Offset to start reading from + /// The table to use for slicing-by-16 lookup + /// Checksum state before this update call + /// A new unfinalized checksum value + /// + /// + /// Assumes input[offset]..input[offset + 15] are valid array indexes. + /// For performance reasons, this must be checked by the caller. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static uint UpdateDataForReversedPoly(byte[] input, int offset, uint[] crcTable, uint checkValue) + { + byte x1 = (byte)((byte)checkValue ^ input[offset]); + byte x2 = (byte)((byte)(checkValue >>= 8) ^ input[offset + 1]); + byte x3 = (byte)((byte)(checkValue >>= 8) ^ input[offset + 2]); + byte x4 = (byte)((byte)(checkValue >>= 8) ^ input[offset + 3]); + + return UpdateDataCommon(input, offset, crcTable, x1, x2, x3, x4); + } + + /// + /// A shared method for updating an unfinalized CRC checksum using slicing-by-16. + /// + /// Array of data to checksum + /// Offset to start reading from + /// The table to use for slicing-by-16 lookup + /// First byte of input after mixing with the old CRC + /// Second byte of input after mixing with the old CRC + /// Third byte of input after mixing with the old CRC + /// Fourth byte of input after mixing with the old CRC + /// A new unfinalized checksum value + /// + /// + /// Even though the first four bytes of input are fed in as arguments, + /// should be the same value passed to this + /// function's caller (either or + /// ). This method will get inlined + /// into both functions, so using the same offset produces faster code. + /// + /// + /// Because most processors running C# have some kind of instruction-level + /// parallelism, the order of XOR operations can affect performance. This + /// ordering assumes that the assembly code generated by the just-in-time + /// compiler will emit a bunch of arithmetic operations for checking array + /// bounds. Then it opportunistically XORs a1 and a2 to keep the processor + /// busy while those other parts of the pipeline handle the range check + /// calculations. + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static uint UpdateDataCommon(byte[] input, int offset, uint[] crcTable, byte x1, byte x2, byte x3, byte x4) + { + uint result; + uint a1 = crcTable[x1 + 3840] ^ crcTable[x2 + 3584]; + uint a2 = crcTable[x3 + 3328] ^ crcTable[x4 + 3072]; + + result = crcTable[input[offset + 4] + 2816]; + result ^= crcTable[input[offset + 5] + 2560]; + a1 ^= crcTable[input[offset + 9] + 1536]; + result ^= crcTable[input[offset + 6] + 2304]; + result ^= crcTable[input[offset + 7] + 2048]; + result ^= crcTable[input[offset + 8] + 1792]; + a2 ^= crcTable[input[offset + 13] + 512]; + result ^= crcTable[input[offset + 10] + 1280]; + result ^= crcTable[input[offset + 11] + 1024]; + result ^= crcTable[input[offset + 12] + 768]; + result ^= a1; + result ^= crcTable[input[offset + 14] + 256]; + result ^= crcTable[input[offset + 15]]; + result ^= a2; + + return result; + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/Checksum/ChecksumTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Checksum/ChecksumTests.cs index b8aefc52f..56c6bb836 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Checksum/ChecksumTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Checksum/ChecksumTests.cs @@ -13,6 +13,14 @@ private readonly // Represents ASCII string of "123456789" byte[] check = { 49, 50, 51, 52, 53, 54, 55, 56, 57 }; + // Represents string "123456789123456789123456789123456789" + private readonly byte[] longCheck = { + 49, 50, 51, 52, 53, 54, 55, 56, 57, + 49, 50, 51, 52, 53, 54, 55, 56, 57, + 49, 50, 51, 52, 53, 54, 55, 56, 57, + 49, 50, 51, 52, 53, 54, 55, 56, 57 + }; + [Test] public void Adler_32() { @@ -70,6 +78,32 @@ public void CRC_32_BZip2() exceptionTesting(underTestBZip2Crc); } + [Test] + public void CRC_32_BZip2_Long() + { + var underTestCrc32 = new BZip2Crc(); + underTestCrc32.Update(longCheck); + Assert.AreEqual(0xEE53D2B2, underTestCrc32.Value); + } + + [Test] + public void CRC_32_BZip2_Unaligned() + { + // Extract "456" and CRC + var underTestCrc32 = new BZip2Crc(); + underTestCrc32.Update(new ArraySegment(check, 3, 3)); + Assert.AreEqual(0x001D0511, underTestCrc32.Value); + } + + [Test] + public void CRC_32_BZip2_Long_Unaligned() + { + // Extract "789123456789123456" and CRC + var underTestCrc32 = new BZip2Crc(); + underTestCrc32.Update(new ArraySegment(longCheck, 15, 18)); + Assert.AreEqual(0x025846E0, underTestCrc32.Value); + } + [Test] public void CRC_32() { @@ -85,6 +119,32 @@ public void CRC_32() exceptionTesting(underTestCrc32); } + [Test] + public void CRC_32_Long() + { + var underTestCrc32 = new Crc32(); + underTestCrc32.Update(longCheck); + Assert.AreEqual(0x3E29169C, underTestCrc32.Value); + } + + [Test] + public void CRC_32_Unaligned() + { + // Extract "456" and CRC + var underTestCrc32 = new Crc32(); + underTestCrc32.Update(new ArraySegment(check, 3, 3)); + Assert.AreEqual(0xB1A8C371, underTestCrc32.Value); + } + + [Test] + public void CRC_32_Long_Unaligned() + { + // Extract "789123456789123456" and CRC + var underTestCrc32 = new Crc32(); + underTestCrc32.Update(new ArraySegment(longCheck, 15, 18)); + Assert.AreEqual(0x31CA9A2E, underTestCrc32.Value); + } + private void exceptionTesting(IChecksum crcUnderTest) { bool exception = false; From 933c41c8bc59ecf43cae0333861265b64628b6a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 21 Nov 2020 13:09:12 +0100 Subject: [PATCH 066/162] PR #475: Fix updating zips with descriptor entries - Unit tests for using ZipFile to update file entries that have descriptors - Fix size calculation in GetDescriptorSize - Handle optional descriptor signature when updating --- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 113 +++++++++++------- .../Zip/ZipFileHandling.cs | 83 +++++++++++++ 2 files changed, 154 insertions(+), 42 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index bce0b609f..62015a932 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1003,16 +1003,19 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl if (this[entryIndex].Crc != data.Crc) { status.AddError(); + resultHandler?.Invoke(status, "Descriptor CRC mismatch"); } if (this[entryIndex].CompressedSize != data.CompressedSize) { status.AddError(); + resultHandler?.Invoke(status, "Descriptor compressed size mismatch"); } if (this[entryIndex].Size != data.Size) { status.AddError(); + resultHandler?.Invoke(status, "Descriptor size mismatch"); } } } @@ -1921,11 +1924,9 @@ public void Modify(ZipEntry original, ZipEntry updated) if ( original == null ) { throw new ArgumentNullException("original"); } - if ( updated == null ) { throw new ArgumentNullException("updated"); } - CheckUpdating(); contentsEdited_ = true; updates_.Add(new ZipUpdate(original, updated)); @@ -2386,26 +2387,37 @@ private byte[] GetBuffer() private void CopyDescriptorBytes(ZipUpdate update, Stream dest, Stream source) { - int bytesToCopy = GetDescriptorSize(update); + // Don't include the signature size to allow copy without seeking + var bytesToCopy = GetDescriptorSize(update, false); + + // Don't touch the source stream if no descriptor is present + if (bytesToCopy == 0) return; - if (bytesToCopy > 0) + var buffer = GetBuffer(); + + // Copy the first 4 bytes of the descriptor + source.Read(buffer, 0, sizeof(int)); + dest.Write(buffer, 0, sizeof(int)); + + if (BitConverter.ToUInt32(buffer, 0) != ZipConstants.DataDescriptorSignature) { - byte[] buffer = GetBuffer(); + // The initial bytes wasn't the descriptor, reduce the pending byte count + bytesToCopy -= buffer.Length; + } - while (bytesToCopy > 0) - { - int readSize = Math.Min(buffer.Length, bytesToCopy); + while (bytesToCopy > 0) + { + int readSize = Math.Min(buffer.Length, bytesToCopy); - int bytesRead = source.Read(buffer, 0, readSize); - if (bytesRead > 0) - { - dest.Write(buffer, 0, bytesRead); - bytesToCopy -= bytesRead; - } - else - { - throw new ZipException("Unxpected end of stream"); - } + int bytesRead = source.Read(buffer, 0, readSize); + if (bytesRead > 0) + { + dest.Write(buffer, 0, bytesRead); + bytesToCopy -= bytesRead; + } + else + { + throw new ZipException("Unxpected end of stream"); } } } @@ -2464,32 +2476,37 @@ private void CopyBytes(ZipUpdate update, Stream destination, Stream source, /// Get the size of the source descriptor for a . /// /// The update to get the size for. - /// The descriptor size, zero if there isnt one. - private int GetDescriptorSize(ZipUpdate update) + /// Whether to include the signature size + /// The descriptor size, zero if there isn't one. + private int GetDescriptorSize(ZipUpdate update, bool includingSignature) { - int result = 0; - if ((update.Entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) - { - result = ZipConstants.DataDescriptorSize - 4; - if (update.Entry.LocalHeaderRequiresZip64) - { - result = ZipConstants.Zip64DataDescriptorSize - 4; - } - } - return result; + if (!((GeneralBitFlags)update.Entry.Flags).HasFlag(GeneralBitFlags.Descriptor)) + return 0; + + var descriptorWithSignature = update.Entry.LocalHeaderRequiresZip64 + ? ZipConstants.Zip64DataDescriptorSize + : ZipConstants.DataDescriptorSize; + + return includingSignature + ? descriptorWithSignature + : descriptorWithSignature - sizeof(int); } private void CopyDescriptorBytesDirect(ZipUpdate update, Stream stream, ref long destinationPosition, long sourcePosition) { - int bytesToCopy = GetDescriptorSize(update); + var buffer = GetBuffer(); ; + + stream.Position = sourcePosition; + stream.Read(buffer, 0, sizeof(int)); + var sourceHasSignature = BitConverter.ToUInt32(buffer, 0) == ZipConstants.DataDescriptorSignature; + + var bytesToCopy = GetDescriptorSize(update, sourceHasSignature); while (bytesToCopy > 0) { - var readSize = (int)bytesToCopy; - byte[] buffer = GetBuffer(); - stream.Position = sourcePosition; - int bytesRead = stream.Read(buffer, 0, readSize); + + var bytesRead = stream.Read(buffer, 0, bytesToCopy); if (bytesRead > 0) { stream.Position = destinationPosition; @@ -2500,7 +2517,7 @@ private void CopyDescriptorBytesDirect(ZipUpdate update, Stream stream, ref long } else { - throw new ZipException("Unxpected end of stream"); + throw new ZipException("Unexpected end of stream"); } } } @@ -2757,6 +2774,7 @@ private void CopyEntryDirect(ZipFile workFile, ZipUpdate update, ref long destin // Clumsy way of handling retrieving the original name and extra data length for now. // TODO: Stop re-reading name and data length in CopyEntryDirect. + uint nameLength = ReadLEUshort(); uint extraLength = ReadLEUshort(); @@ -2765,14 +2783,25 @@ private void CopyEntryDirect(ZipFile workFile, ZipUpdate update, ref long destin if (skipOver) { if (update.OffsetBasedSize != -1) + { destinationPosition += update.OffsetBasedSize; + } else - // TODO: Find out why this calculation comes up 4 bytes short on some entries in ODT (Office Document Text) archives. - // WinZip produces a warning on these entries: - // "caution: value of lrec.csize (compressed size) changed from ..." - destinationPosition += - (sourcePosition - entryDataOffset) + NameLengthOffset + // Header size - update.Entry.CompressedSize + GetDescriptorSize(update); + { + // Skip entry header + destinationPosition += (sourcePosition - entryDataOffset) + NameLengthOffset; + + // Skip entry compressed data + destinationPosition += update.Entry.CompressedSize; + + // Seek to end of entry to check for descriptor signature + baseStream_.Seek(destinationPosition, SeekOrigin.Begin); + + var descriptorHasSignature = ReadLEUint() == ZipConstants.DataDescriptorSignature; + + // Skip descriptor and it's signature (if present) + destinationPosition += GetDescriptorSize(update, descriptorHasSignature); + } } else { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index 4a43211fe..c92dae280 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -1755,5 +1755,88 @@ public void ShouldReadAESBZip2ZipCreatedBy7Zip() } } } + + /// + /// Test for https://github.com/icsharpcode/SharpZipLib/issues/147, when deleting items in a zip + /// + /// Whether Zip64 should be used in the test archive + [TestCase(UseZip64.On)] + [TestCase(UseZip64.Off)] + [Category("Zip")] + public void TestDescriptorUpdateOnDelete(UseZip64 useZip64) + { + MemoryStream msw = new MemoryStreamWithoutSeek(); + using (ZipOutputStream outStream = new ZipOutputStream(msw)) + { + outStream.UseZip64 = useZip64; + outStream.IsStreamOwner = false; + outStream.PutNextEntry(new ZipEntry("StripedMarlin")); + outStream.WriteByte(89); + + outStream.PutNextEntry(new ZipEntry("StripedMarlin2")); + outStream.WriteByte(91); + } + + var zipData = msw.ToArray(); + Assert.IsTrue(ZipTesting.TestArchive(zipData)); + + using (var memoryStream = new MemoryStream(zipData)) + { + using (var zipFile = new ZipFile(memoryStream, leaveOpen: true)) + { + zipFile.BeginUpdate(); + zipFile.Delete("StripedMarlin"); + zipFile.CommitUpdate(); + } + + memoryStream.Position = 0; + + using (var zipFile = new ZipFile(memoryStream, leaveOpen: true)) + { + Assert.That(zipFile.TestArchive(true), Is.True); + } + } + } + + /// + /// Test for https://github.com/icsharpcode/SharpZipLib/issues/147, when adding items to a zip + /// + /// Whether Zip64 should be used in the test archive + [TestCase(UseZip64.On)] + [TestCase(UseZip64.Off)] + [Category("Zip")] + public void TestDescriptorUpdateOnAdd(UseZip64 useZip64) + { + MemoryStream msw = new MemoryStreamWithoutSeek(); + using (ZipOutputStream outStream = new ZipOutputStream(msw)) + { + outStream.UseZip64 = useZip64; + outStream.IsStreamOwner = false; + outStream.PutNextEntry(new ZipEntry("StripedMarlin")); + outStream.WriteByte(89); + } + + var zipData = msw.ToArray(); + Assert.IsTrue(ZipTesting.TestArchive(zipData)); + + using (var memoryStream = new MemoryStream()) + { + memoryStream.Write(zipData, 0, zipData.Length); + + using (var zipFile = new ZipFile(memoryStream, leaveOpen: true)) + { + zipFile.BeginUpdate(); + zipFile.Add(new StringMemoryDataSource("stripey"), "Zebra"); + zipFile.CommitUpdate(); + } + + memoryStream.Position = 0; + + using (var zipFile = new ZipFile(memoryStream, leaveOpen: true)) + { + Assert.That(zipFile.TestArchive(true), Is.True); + } + } + } } } From c5c187dacaf20f9ba054a0eb5b8c56cc45d2894b Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 21 Nov 2020 12:39:59 +0000 Subject: [PATCH 067/162] PR #475: Fix updating zips with descriptor entries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dummy commit since Github didn't recognize the merge Co-authored-by: nils måsén From ea941dd45938c6ee25760c6f888e2f4c043d06f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 21 Nov 2020 13:59:38 +0100 Subject: [PATCH 068/162] PR #541: Update csproj for new release --- .../ICSharpCode.SharpZipLib.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index 73509ec61..03dcc861d 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -11,9 +11,9 @@ - 1.3.0.8 - 1.2.0.8 - 1.3.0 + 1.3.1.9 + 1.3.1.9 + 1.3.1 SharpZipLib ICSharpCode ICSharpCode @@ -26,7 +26,7 @@ Compression Library Zip GZip BZip2 LZW Tar en-US -Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3 for more information. +Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.1 for more information. https://github.com/icsharpcode/SharpZipLib From 6170ef4f60332583cd3ee4c48a61868295cda7d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 21 Nov 2020 16:11:43 +0100 Subject: [PATCH 069/162] CI: run master build on release --- .github/workflows/on-push.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 6b09c2b4d..14b49d357 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -6,6 +6,7 @@ env: on: push: branches: [ master ] + release: jobs: BuildAndTest: From b7bc4e08620f4410b721a3bd59fe53537f774909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 22 Nov 2020 17:17:41 +0100 Subject: [PATCH 070/162] #542: Build and publish documentation on release --- .github/workflows/release.yml | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e5cf14563..60d98ba9f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -24,20 +24,16 @@ jobs: with: args: docs/help/docfx.json -# Disabled until know to be working -# - uses: JamesIves/github-pages-deploy-action@3.6.2 -# name: Publish documentation to Github Pages -# with: -# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -# BRANCH: gh-pages -# -# # The folder the action should deploy. -# FOLDER: _site -# -# # Automatically remove deleted files from the deploy branch -# CLEAN: true + - uses: JamesIves/github-pages-deploy-action@3.6.2 + name: Publish documentation to Github Pages + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BRANCH: gh-pages + FOLDER: docs/help/_site + TARGET_FOLDER: help + CLEAN: false - name: Upload documentation as artifact uses: actions/upload-artifact@v2 with: - path: _site + path: docs/help/_site From fec479c2e1a2c7cd58ba8319450901fe40eb070f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 19 Dec 2020 13:35:48 +0100 Subject: [PATCH 071/162] PR #553: Remove broken codacy integration --- .github/workflows/pull-request.yml | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index aedb7fc5e..72f6556d2 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -61,21 +61,7 @@ jobs: - name: Run tests run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.target }} --no-restore - - Codacy-Analysis: - runs-on: ubuntu-latest - name: Codacy Analysis CLI - steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Run codacy-analysis-cli - uses: codacy/codacy-analysis-cli-action@1.1.0 - with: - # The current issues needs to be fixed before this can be removed - max-allowed-issues: 9999 - project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} - upload: true - + Pack: needs: [Build, Test] runs-on: windows-latest From f044a6c74b8eb6b00ad13822d07e9cec5279700f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Luthi?= Date: Sat, 6 Feb 2021 08:06:08 +0100 Subject: [PATCH 072/162] PR #549: Add .NET Standard 2.1 target framework Also fix the .NET Standard 2.0 target framework moniker: netstandard2.0 instead of netstandard2, see https://docs.microsoft.com/en-us/dotnet/standard/frameworks#supported-target-frameworks --- .github/workflows/on-push.yml | 3 +-- .github/workflows/pull-request.yml | 9 +++++---- .travis.yml | 4 ++-- .../ICSharpCode.SharpZipLib.csproj | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 14b49d357..1ef2bafad 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -16,7 +16,7 @@ jobs: matrix: configuration: [debug, release] os: [ubuntu, windows, macos] - libtarget: [netstandard2] + libtarget: [netstandard2.0, netstandard2.1] testtarget: [netcoreapp3.1] include: - configuration: debug @@ -31,7 +31,6 @@ jobs: - uses: actions/checkout@v2 - name: Setup .NET Core - if: matrix.libtarget == 'netstandard2' uses: actions/setup-dotnet@v1 with: dotnet-version: '3.1.x' diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 72f6556d2..497152fc4 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -12,7 +12,7 @@ jobs: matrix: configuration: [debug, release] os: [ubuntu, windows, macos] - target: [netstandard2] + target: [netstandard2.0, netstandard2.1] include: - configuration: Debug os: windows @@ -24,7 +24,6 @@ jobs: - uses: actions/checkout@v2 - name: Setup .NET Core - if: matrix.target == 'netstandard2' uses: actions/setup-dotnet@v1 with: dotnet-version: '3.1.x' @@ -78,8 +77,10 @@ jobs: with: dotnet-version: '3.1.x' - - name: Build library for .NET Standard 2 - run: dotnet build -c Release -f netstandard2 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library for .NET Standard 2.0 + run: dotnet build -c Release -f netstandard2.0 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library for .NET Standard 2.1 + run: dotnet build -c Release -f netstandard2.1 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - name: Build library for .NET Framework 4.5 run: dotnet build -c Release -f net45 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj diff --git a/.travis.yml b/.travis.yml index 9b54b3f9d..1e76533f4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,14 +15,14 @@ install: # - nuget restore ICSharpCode.SharpZipLib.sln # - nuget install NUnit.Console -Version 3.8.0 -OutputDirectory _testRunner script: - - dotnet build -f netstandard2 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - dotnet build -f netstandard2.0 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - dotnet run -c Debug -f netcoreapp2 -p test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj -- --where "class !~ WindowsNameTransformHandling & test !~ ZipEntryFactoryHandling.CreatedValues & test !~ ZipNameTransformHandling.FilenameCleaning" --result=docs/nunit3-test-results-debug.xml - dotnet run -c Release -f netcoreapp2 -p test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj -- --where "class !~ WindowsNameTransformHandling & test !~ ZipEntryFactoryHandling.CreatedValues & test !~ ZipNameTransformHandling.FilenameCleaning" --result=docs\nunit3-test-results-release.xml # - dotnet test test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj # - xbuild /p:Configuration=Release ICSharpCode.SharpZipLib.sln # - mono ./packages/NUnit.ConsoleRunner.3.2.1/tools/nunit3-console.exe --framework=mono-4.0 --labels=All --result=./Documentation/nunit3-test-results-travis.xml ./bin/Release/ICSharpCode.SharpZipLib.Tests.dll after_script: - - dotnet pack -f netstandard2 -o _dist/ src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - dotnet pack -f netstandard2.0 -o _dist/ src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj #cache: # directories: # - bin diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index 03dcc861d..6248b6287 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -1,7 +1,7 @@  - netstandard2;net45 + netstandard2.0;netstandard2.1;net45 True ../../assets/ICSharpCode.SharpZipLib.snk true From 89e7bdd9fe9ee7e2edebd7434de944277959571f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 6 Feb 2021 08:08:06 +0100 Subject: [PATCH 073/162] PR #554: Skip CRC calculation for AES zip entries --- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 17 +++++++-- .../Zip/ZipHelperStream.cs | 4 +- .../Zip/ZipOutputStream.cs | 38 ++++++++++++------- .../Zip/FastZipHandling.cs | 7 +++- 4 files changed, 46 insertions(+), 20 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 62015a932..6daeb7521 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -960,6 +960,9 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl if (testing && testData && this[entryIndex].IsFile) { + // Don't check CRC for AES encrypted archives + var checkCRC = this[entryIndex].AESKeySize == 0; + if (resultHandler != null) { status.SetOperation(TestOperation.EntryData); @@ -975,7 +978,10 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl int bytesRead; while ((bytesRead = entryStream.Read(buffer, 0, buffer.Length)) > 0) { - crc.Update(new ArraySegment(buffer, 0, bytesRead)); + if (checkCRC) + { + crc.Update(new ArraySegment(buffer, 0, bytesRead)); + } if (resultHandler != null) { @@ -986,7 +992,7 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl } } - if (this[entryIndex].Crc != crc.Value) + if (checkCRC && this[entryIndex].Crc != crc.Value) { status.AddError(); @@ -1000,7 +1006,8 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl var helper = new ZipHelperStream(baseStream_); var data = new DescriptorData(); helper.ReadDataDescriptor(this[entryIndex].LocalHeaderRequiresZip64, data); - if (this[entryIndex].Crc != data.Crc) + + if (checkCRC && this[entryIndex].Crc != data.Crc) { status.AddError(); resultHandler?.Invoke(status, "Descriptor CRC mismatch"); @@ -2687,6 +2694,8 @@ private void AddEntry(ZipFile workFile, ZipUpdate update) } } + var useCrc = update.Entry.AESKeySize == 0; + if (source != null) { using (source) @@ -2711,7 +2720,7 @@ private void AddEntry(ZipFile workFile, ZipUpdate update) using (Stream output = workFile.GetOutputStream(update.OutEntry)) { - CopyBytes(update, output, source, sourceStreamLength, true); + CopyBytes(update, output, source, sourceStreamLength, useCrc); } long dataEnd = workFile.baseStream_.Position; diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs index dd7d25d94..da65630c6 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs @@ -565,7 +565,7 @@ public int WriteDataDescriptor(ZipEntry entry) if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) { // The signature is not PKZIP originally but is now described as optional - // in the PKZIP Appnote documenting trhe format. + // in the PKZIP Appnote documenting the format. WriteLEInt(ZipConstants.DataDescriptorSignature); WriteLEInt(unchecked((int)(entry.Crc))); @@ -599,7 +599,7 @@ public void ReadDataDescriptor(bool zip64, DescriptorData data) int intValue = ReadLEInt(); // In theory this may not be a descriptor according to PKZIP appnote. - // In practise its always there. + // In practice its always there. if (intValue != ZipConstants.DataDescriptorSignature) { throw new ZipException("Data descriptor signature not found"); diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index b9131d040..3c49ec8cb 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -500,6 +500,9 @@ public void PutNextEntry(ZipEntry entry) /// /// Closes the current entry, updating header and footer information as required /// + /// + /// Invalid entry field values. + /// /// /// An I/O error occurs. /// @@ -530,7 +533,7 @@ public void CloseEntry() } else if (curMethod == CompressionMethod.Stored) { - // This is done by Finsh() for Deflated entries, but we need to do it + // This is done by Finish() for Deflated entries, but we need to do it // ourselves for Stored ones base.GetAuthCodeIfAES(); } @@ -539,6 +542,19 @@ public void CloseEntry() if (curEntry.AESKeySize > 0) { baseOutputStream_.Write(AESAuthCode, 0, 10); + // Always use 0 as CRC for AE-2 format + curEntry.Crc = 0; + } + else + { + if (curEntry.Crc < 0) + { + curEntry.Crc = crc.Value; + } + else if (curEntry.Crc != crc.Value) + { + throw new ZipException($"crc was {crc.Value}, but {curEntry.Crc} was expected"); + } } if (curEntry.Size < 0) @@ -547,7 +563,7 @@ public void CloseEntry() } else if (curEntry.Size != size) { - throw new ZipException("size was " + size + ", but I expected " + curEntry.Size); + throw new ZipException($"size was {size}, but {curEntry.Size} was expected"); } if (curEntry.CompressedSize < 0) @@ -556,16 +572,7 @@ public void CloseEntry() } else if (curEntry.CompressedSize != csize) { - throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize); - } - - if (curEntry.Crc < 0) - { - curEntry.Crc = crc.Value; - } - else if (curEntry.Crc != crc.Value) - { - throw new ZipException("crc was " + crc.Value + ", but I expected " + curEntry.Crc); + throw new ZipException($"compressed size was {csize}, but {curEntry.CompressedSize} expected"); } offset += csize; @@ -718,7 +725,12 @@ public override void Write(byte[] buffer, int offset, int count) throw new ArgumentException("Invalid offset/count combination"); } - crc.Update(new ArraySegment(buffer, offset, count)); + if (curEntry.AESKeySize == 0) + { + // Only update CRC if AES is not enabled + crc.Update(new ArraySegment(buffer, offset, count)); + } + size += count; switch (curMethod) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 753fc8623..8be25a4dc 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -193,7 +193,12 @@ public void Encryption(ZipEncryptionMethod encryptionMethod) ZipEntry entry = zf[0]; Assert.AreEqual(tempName1, entry.Name); Assert.AreEqual(1, entry.Size); - Assert.IsTrue(zf.TestArchive(true)); + Assert.IsTrue(zf.TestArchive(true, TestStrategy.FindFirstError, (status, message) => + { + if(!string.IsNullOrEmpty(message)) { + Console.WriteLine($"{message} ({status.Entry?.Name ?? "-"})"); + } + })); Assert.IsTrue(entry.IsCrypted); switch (encryptionMethod) From 703c877b202bd6e72639e02f7348119456496d31 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 6 Feb 2021 15:35:17 +0000 Subject: [PATCH 074/162] PR #546: Make pure private functions static --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index 3baf8415d..2f326ab0e 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -1125,7 +1125,7 @@ internal void ProcessExtraData(bool localHeader) } } - private DateTime? GetDateTime(ZipExtraData extraData) + private static DateTime? GetDateTime(ZipExtraData extraData) { // Check for NT timestamp // NOTE: Disable by default to match behavior of InfoZIP diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 6daeb7521..704911b3f 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1911,7 +1911,7 @@ public void AddDirectory(string directoryName) /// Check if the specified compression method is supported for adding a new entry. /// /// The compression method for the new entry. - private void CheckSupportedCompressionMethod(CompressionMethod compressionMethod) + private static void CheckSupportedCompressionMethod(CompressionMethod compressionMethod) { if (compressionMethod != CompressionMethod.Deflated && compressionMethod != CompressionMethod.Stored && compressionMethod != CompressionMethod.BZip2) { From 33da79179e1e3fbdb9939d0aa6a54005af320553 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 6 Feb 2021 15:49:43 +0000 Subject: [PATCH 075/162] PR #533: Convert the C# sample projects to PackageReference format MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Convert the C# sample projects to PackageReference format * Update example package ref to v1.3.1 Co-authored-by: nils måsén --- .../cs/Cmd_BZip2/Cmd_BZip2.csproj | 11 ++++++----- .../cs/Cmd_BZip2/packages.config | 4 ---- .../cs/Cmd_Checksum/Cmd_Checksum.csproj | 11 ++++++----- .../cs/Cmd_Checksum/packages.config | 4 ---- .../cs/Cmd_GZip/Cmd_GZip.csproj | 11 ++++++----- .../cs/Cmd_GZip/packages.config | 4 ---- .../cs/Cmd_Tar/Cmd_Tar.csproj | 11 ++++++----- .../cs/Cmd_Tar/packages.config | 4 ---- .../cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj | 11 ++++++----- .../cs/Cmd_ZipInfo/packages.config | 4 ---- .../cs/CreateZipFile/CreateZipFile.csproj | 11 ++++++----- .../cs/CreateZipFile/packages.config | 4 ---- .../cs/FastZip/FastZip.csproj | 8 ++++++-- .../cs/FastZip/packages.config | 4 ---- .../cs/sz/packages.config | 4 ---- .../ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj | 11 ++++++----- .../cs/unzipfile/packages.config | 4 ---- .../cs/unzipfile/unzipfile.csproj | 11 ++++++----- .../cs/viewzipfile/packages.config | 4 ---- .../cs/viewzipfile/viewzipfile.csproj | 11 ++++++----- .../cs/zf/packages.config | 4 ---- .../ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj | 11 ++++++----- 22 files changed, 66 insertions(+), 96 deletions(-) delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj index 121410932..07039ab9d 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj @@ -80,9 +80,6 @@ copy Cmd_BZip2.exe bunzip2.exe 4096 - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -91,7 +88,6 @@ copy Cmd_BZip2.exe bunzip2.exe - @@ -103,5 +99,10 @@ copy Cmd_BZip2.exe bunzip2.exe + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj index 7bfc3d9c2..1509d6080 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj @@ -74,9 +74,6 @@ true - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -90,7 +87,6 @@ - @@ -102,5 +98,10 @@ + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj index ce1d46a9a..d5e021825 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj @@ -74,9 +74,6 @@ copy Cmd_GZip.exe gunzip.exe true - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -90,7 +87,6 @@ copy Cmd_GZip.exe gunzip.exe - @@ -102,5 +98,10 @@ copy Cmd_GZip.exe gunzip.exe + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj index e002adadf..4f6bb416a 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj @@ -66,9 +66,6 @@ Cmd_Tar - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -84,7 +81,6 @@ - @@ -93,8 +89,13 @@ true + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj index 7cb8118c7..0e3d31240 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj @@ -73,9 +73,6 @@ true - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -89,7 +86,6 @@ - @@ -101,5 +97,10 @@ + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj index 08cc046ff..61dcf0166 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj @@ -81,9 +81,6 @@ - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -97,7 +94,6 @@ - @@ -109,5 +105,10 @@ + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj index 5bcd65546..6a948c6b5 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj @@ -80,7 +80,6 @@ - @@ -89,5 +88,10 @@ true + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj index a749293f9..02a096db6 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj @@ -62,9 +62,6 @@ false - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -78,7 +75,6 @@ - @@ -87,5 +83,10 @@ true + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj index 3d8ca89e8..fa3f6b8fc 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj @@ -38,9 +38,6 @@ UnZipFileClass - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -58,11 +55,15 @@ - + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj index 531d502c4..0b10efd15 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj @@ -38,9 +38,6 @@ ViewZipFileClass - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -58,11 +55,15 @@ - + + + 1.3.1 + + - \ No newline at end of file + diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj index 9013296b9..e8d8b757f 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj @@ -62,9 +62,6 @@ false - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -78,7 +75,6 @@ - @@ -87,5 +83,10 @@ true + + + 1.3.1 + + - \ No newline at end of file + From 11936722e54806431276e9fe67c4a8d16e66b748 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 6 Feb 2021 16:17:47 +0000 Subject: [PATCH 076/162] PR #457: add basic async unit tests for the inflator/deflator streams MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add some basic async unit tests for the deflator streams Co-authored-by: nils måsén --- .../Base/InflaterDeflaterTests.cs | 161 +++++++++++++----- 1 file changed, 121 insertions(+), 40 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs index cf7b72456..6aff0a693 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs @@ -6,6 +6,7 @@ using System.IO; using System.Security; using System.Text; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.Base { @@ -17,17 +18,13 @@ public class InflaterDeflaterTestSuite { private void Inflate(MemoryStream ms, byte[] original, int level, bool zlib) { - ms.Seek(0, SeekOrigin.Begin); - - var inflater = new Inflater(!zlib); - var inStream = new InflaterInputStream(ms, inflater); byte[] buf2 = new byte[original.Length]; - int currentIndex = 0; - int count = buf2.Length; - - try + using (var inStream = GetInflaterInputStream(ms, zlib)) { + int currentIndex = 0; + int count = buf2.Length; + while (true) { int numRead = inStream.Read(buf2, currentIndex, count); @@ -38,19 +35,106 @@ private void Inflate(MemoryStream ms, byte[] original, int level, bool zlib) currentIndex += numRead; count -= numRead; } + + Assert.That(currentIndex, Is.EqualTo(original.Length), "Decompressed data must have the same length as the original data"); } - catch (Exception ex) + + VerifyInflatedData(original, buf2, level, zlib); + } + + private MemoryStream Deflate(byte[] data, int level, bool zlib) + { + var memoryStream = new MemoryStream(); + + var deflater = new Deflater(level, !zlib); + using (DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater)) + { + outStream.IsStreamOwner = false; + outStream.Write(data, 0, data.Length); + outStream.Flush(); + outStream.Finish(); + } + return memoryStream; + } + + private static byte[] GetRandomTestData(int size) + { + byte[] buffer = new byte[size]; + var rnd = new Random(); + rnd.NextBytes(buffer); + + return buffer; + } + + private void RandomDeflateInflate(int size, int level, bool zlib) + { + byte[] buffer = GetRandomTestData(size); + + MemoryStream ms = Deflate(buffer, level, zlib); + Inflate(ms, buffer, level, zlib); + } + + private static InflaterInputStream GetInflaterInputStream(Stream compressedStream, bool zlib) + { + compressedStream.Seek(0, SeekOrigin.Begin); + + var inflater = new Inflater(!zlib); + var inStream = new InflaterInputStream(compressedStream, inflater); + + return inStream; + } + + private async Task InflateAsync(MemoryStream ms, byte[] original, int level, bool zlib) + { + byte[] buf2 = new byte[original.Length]; + + using (var inStream = GetInflaterInputStream(ms, zlib)) { - Console.WriteLine("Unexpected exception - '{0}'", ex.Message); - throw; + int currentIndex = 0; + int count = buf2.Length; + + while (true) + { + int numRead = await inStream.ReadAsync(buf2, currentIndex, count); + if (numRead <= 0) + { + break; + } + currentIndex += numRead; + count -= numRead; + } + + Assert.That(currentIndex, Is.EqualTo(original.Length), "Decompressed data must have the same length as the original data"); } - if (currentIndex != original.Length) + VerifyInflatedData(original, buf2, level, zlib); + } + + private async Task DeflateAsync(byte[] data, int level, bool zlib) + { + var memoryStream = new MemoryStream(); + + var deflater = new Deflater(level, !zlib); + using (DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater)) { - Console.WriteLine("Original {0}, new {1}", original.Length, currentIndex); - Assert.Fail("Lengths different"); + outStream.IsStreamOwner = false; + await outStream.WriteAsync(data, 0, data.Length); + await outStream.FlushAsync(); + outStream.Finish(); } + return memoryStream; + } + + private async Task RandomDeflateInflateAsync(int size, int level, bool zlib) + { + byte[] buffer = GetRandomTestData(size); + MemoryStream ms = await DeflateAsync(buffer, level, zlib); + await InflateAsync(ms, buffer, level, zlib); + } + + private void VerifyInflatedData(byte[] original, byte[] buf2, int level, bool zlib) + { for (int i = 0; i < original.Length; ++i) { if (buf2[i] != original[i]) @@ -74,31 +158,6 @@ private void Inflate(MemoryStream ms, byte[] original, int level, bool zlib) } } - private MemoryStream Deflate(byte[] data, int level, bool zlib) - { - var memoryStream = new MemoryStream(); - - var deflater = new Deflater(level, !zlib); - using (DeflaterOutputStream outStream = new DeflaterOutputStream(memoryStream, deflater)) - { - outStream.IsStreamOwner = false; - outStream.Write(data, 0, data.Length); - outStream.Flush(); - outStream.Finish(); - } - return memoryStream; - } - - private void RandomDeflateInflate(int size, int level, bool zlib) - { - byte[] buffer = new byte[size]; - var rnd = new Random(); - rnd.NextBytes(buffer); - - MemoryStream ms = Deflate(buffer, level, zlib); - Inflate(ms, buffer, level, zlib); - } - /// /// Basic inflate/deflate test /// @@ -109,12 +168,23 @@ public void InflateDeflateZlib([Range(0, 9)] int level) RandomDeflateInflate(100000, level, true); } + /// + /// Basic async inflate/deflate test + /// + [Test] + [Category("Base")] + [Category("Async")] + public async Task InflateDeflateZlibAsync([Range(0, 9)] int level) + { + await RandomDeflateInflateAsync(100000, level, true); + } + private delegate void RunCompress(byte[] buffer); private int runLevel; private bool runZlib; private long runCount; - private Random runRandom = new Random(5); + private readonly Random runRandom = new Random(5); private void DeflateAndInflate(byte[] buffer) { @@ -169,6 +239,17 @@ public void InflateDeflateNonZlib([Range(0, 9)] int level) RandomDeflateInflate(100000, level, false); } + /// + /// Basic async inflate/deflate test + /// + [Test] + [Category("Base")] + [Category("Async")] + public async Task InflateDeflateNonZlibAsync([Range(0, 9)] int level) + { + await RandomDeflateInflateAsync(100000, level, false); + } + [Test] [Category("Base")] From 3d93ae5078d66c34915dfb77f925d0cdd01ba2e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 13 Feb 2021 14:59:44 +0100 Subject: [PATCH 077/162] chore(ci): fix windows ci env restore See https://github.com/actions/virtual-environments/issues/1090 --- .github/workflows/pull-request.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 497152fc4..7ff7c5073 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -55,6 +55,11 @@ jobs: with: dotnet-version: '3.1.x' + # NOTE: This is the temporary fix for https://github.com/actions/virtual-environments/issues/1090 + - name: Cleanup before restor + if: ${{ matrix.os == 'windows' }} + run: dotnet clean ICSharpCode.SharpZipLib.sln -c ${{ matrix.configuration }} && dotnet nuget locals all --clear + - name: Restore test dependencies run: dotnet restore From b29bf5648f3760d2f9a791b425a59a6ebe7d7ac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 13 Feb 2021 15:12:03 +0100 Subject: [PATCH 078/162] chore(ci): remove config from matrix --- .github/workflows/pull-request.yml | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index 7ff7c5073..ede297174 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -10,7 +10,6 @@ jobs: strategy: fail-fast: false matrix: - configuration: [debug, release] os: [ubuntu, windows, macos] target: [netstandard2.0, netstandard2.1] include: @@ -28,15 +27,17 @@ jobs: with: dotnet-version: '3.1.x' - - name: Build library - run: dotnet build -c ${{ matrix.configuration }} -f ${{ matrix.target }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library (Debug) + run: dotnet build -c debug -f ${{ matrix.target }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + + - name: Build library (Release) + run: dotnet build -c release -f ${{ matrix.target }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj Test: runs-on: ${{ matrix.os }}-latest strategy: fail-fast: false matrix: - configuration: [debug, release] os: [ubuntu, windows, macos] target: [netcoreapp3.1] include: @@ -56,15 +57,18 @@ jobs: dotnet-version: '3.1.x' # NOTE: This is the temporary fix for https://github.com/actions/virtual-environments/issues/1090 - - name: Cleanup before restor + - name: Cleanup before restore if: ${{ matrix.os == 'windows' }} - run: dotnet clean ICSharpCode.SharpZipLib.sln -c ${{ matrix.configuration }} && dotnet nuget locals all --clear + run: dotnet clean ICSharpCode.SharpZipLib.sln && dotnet nuget locals all --clear - name: Restore test dependencies run: dotnet restore - - name: Run tests - run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.target }} --no-restore + - name: Run tests (Debug) + run: dotnet test -c debug -f ${{ matrix.target }} --no-restore + + - name: Run tests (Release) + run: dotnet test -c release -f ${{ matrix.target }} --no-restore Pack: needs: [Build, Test] From c8148775ebf5f04c7da7acc4fce2cdf7775d2322 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 13 Feb 2021 14:56:04 +0000 Subject: [PATCH 079/162] PR #510: Build the test bootstrapper app as netcoreapp3.1 instead of netcoreapp2.0 --- .../ICSharpCode.SharpZipLib.TestBootstrapper.csproj | 2 +- tools/appveyor-test.ps1 | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj b/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj index 3f599186e..0218e5d4d 100644 --- a/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj +++ b/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.0 + netcoreapp3.1 diff --git a/tools/appveyor-test.ps1 b/tools/appveyor-test.ps1 index b46519cb6..0005b5c3d 100644 --- a/tools/appveyor-test.ps1 +++ b/tools/appveyor-test.ps1 @@ -5,7 +5,7 @@ $resxml = ".\docs\nunit3-test-results-debug.xml"; #$tester = "nunit3-console .\test\ICSharpCode.SharpZipLib.Tests\bin\$($env:CONFIGURATION)\netcoreapp2.0\ICSharpCode.SharpZipLib.Tests.dll" # Bootstrapper: -$tester = "dotnet run -f netcoreapp2 -p $proj -c $env:CONFIGURATION"; +$tester = "dotnet run -f netcoreapp3.1 -p $proj -c $env:CONFIGURATION"; iex "$tester --explore=tests.xml"; [xml]$xml = Get-Content("tests.xml"); From 3617fb97699e0fd816586ad0be28220cca82fa87 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 21 Feb 2021 16:41:14 +0000 Subject: [PATCH 080/162] PR #577: Throw ZipException in ZipAESStream instead of generic Exception --- src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs index 4f649e8a9..4bf01300b 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs @@ -2,6 +2,7 @@ using System.IO; using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Core; +using ICSharpCode.SharpZipLib.Zip; namespace ICSharpCode.SharpZipLib.Encryption { @@ -137,14 +138,14 @@ private int ReadAndTransform(byte[] buffer, int offset, int count) nBytes += TransformAndBufferBlock(buffer, offset, bytesLeftToRead, finalBlock); } else if (byteCount < AUTH_CODE_LENGTH) - throw new Exception("Internal error missed auth code"); // Coding bug + throw new ZipException("Internal error missed auth code"); // Coding bug // Final block done. Check Auth code. byte[] calcAuthCode = _transform.GetAuthCode(); for (int i = 0; i < AUTH_CODE_LENGTH; i++) { if (calcAuthCode[i] != _slideBuffer[_slideBufStartPos + i]) { - throw new Exception("AES Authentication Code does not match. This is a super-CRC check on the data in the file after compression and encryption. \r\n" + throw new ZipException("AES Authentication Code does not match. This is a super-CRC check on the data in the file after compression and encryption. \r\n" + "The file may be damaged."); } } From 85f20dcc0eccea1b8ee2bbed3bf774883e0d7619 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 21 Feb 2021 16:41:56 +0000 Subject: [PATCH 081/162] PR #578: Fix typos in the StreamDecodingException doc comments --- .../Core/Exceptions/StreamDecodingException.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Core/Exceptions/StreamDecodingException.cs b/src/ICSharpCode.SharpZipLib/Core/Exceptions/StreamDecodingException.cs index 389b7d065..e22b11b0d 100644 --- a/src/ICSharpCode.SharpZipLib/Core/Exceptions/StreamDecodingException.cs +++ b/src/ICSharpCode.SharpZipLib/Core/Exceptions/StreamDecodingException.cs @@ -4,8 +4,8 @@ namespace ICSharpCode.SharpZipLib { /// - /// Indicates that an error occured during decoding of a input stream due to corrupt - /// data or (unintentional) library incompability. + /// Indicates that an error occurred during decoding of a input stream due to corrupt + /// data or (unintentional) library incompatibility. /// [Serializable] public class StreamDecodingException : SharpZipBaseException From 06ff713469fd6e1c1cdd2ad3b364248e457a1b96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 21 Feb 2021 17:46:39 +0100 Subject: [PATCH 082/162] PR #517: Throw exception on Store+Descriptor entries * fix(zip): indicate that store/desc. entries cant be extracted * style(zip): simplify and fix spelling * fix(zip): check decompress support after specific exception handling * test: use random bad path instead of possible network drive * docs(zip): remove explicit mentions of methods in CompressionMethod * fix(zip): remove superfluous null check --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 481 +++++------------- .../Zip/ZipEntryExtensions.cs | 32 ++ .../Zip/ZipInputStream.cs | 62 ++- .../Zip/FastZipHandling.cs | 16 +- .../Zip/StreamHandling.cs | 36 ++ 5 files changed, 249 insertions(+), 378 deletions(-) create mode 100644 src/ICSharpCode.SharpZipLib/Zip/ZipEntryExtensions.cs diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index 2f326ab0e..c607cf9f2 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -263,13 +263,7 @@ public ZipEntry(ZipEntry entry) /// /// Get a value indicating whether the entry has a CRC value available. /// - public bool HasCrc - { - get - { - return (known & Known.Crc) != 0; - } - } + public bool HasCrc => (known & Known.Crc) != 0; /// /// Get/Set flag indicating if entry is encrypted. @@ -278,21 +272,8 @@ public bool HasCrc /// This is an assistant that interprets the flags property. public bool IsCrypted { - get - { - return (flags & 1) != 0; - } - set - { - if (value) - { - flags |= 1; - } - else - { - flags &= ~1; - } - } + get => this.HasFlag(GeneralBitFlags.Encrypted); + set => this.SetFlag(GeneralBitFlags.Encrypted, value); } /// @@ -302,21 +283,8 @@ public bool IsCrypted /// This is an assistant that interprets the flags property. public bool IsUnicodeText { - get - { - return (flags & (int)GeneralBitFlags.UnicodeText) != 0; - } - set - { - if (value) - { - flags |= (int)GeneralBitFlags.UnicodeText; - } - else - { - flags &= ~(int)GeneralBitFlags.UnicodeText; - } - } + get => this.HasFlag(GeneralBitFlags.UnicodeText); + set => this.SetFlag(GeneralBitFlags.UnicodeText, value); } /// @@ -324,15 +292,8 @@ public bool IsUnicodeText /// internal byte CryptoCheckValue { - get - { - return cryptoCheckValue_; - } - - set - { - cryptoCheckValue_ = value; - } + get => cryptoCheckValue_; + set => cryptoCheckValue_ = value; } /// @@ -368,14 +329,8 @@ internal byte CryptoCheckValue /// public int Flags { - get - { - return flags; - } - set - { - flags = value; - } + get => flags; + set => flags = value; } /// @@ -384,14 +339,8 @@ public int Flags /// This is only valid when the entry is part of a public long ZipFileIndex { - get - { - return zipFileIndex; - } - set - { - zipFileIndex = value; - } + get => zipFileIndex; + set => zipFileIndex = value; } /// @@ -399,34 +348,18 @@ public long ZipFileIndex /// public long Offset { - get - { - return offset; - } - set - { - offset = value; - } + get => offset; + set => offset = value; } /// /// Get/Set external file attributes as an integer. - /// The values of this are operating system dependant see + /// The values of this are operating system dependent see /// HostSystem for details /// public int ExternalFileAttributes { - get - { - if ((known & Known.ExternalAttributes) == 0) - { - return -1; - } - else - { - return externalFileAttributes; - } - } + get => (known & Known.ExternalAttributes) == 0 ? -1 : externalFileAttributes; set { @@ -440,25 +373,14 @@ public int ExternalFileAttributes /// The value / 10 indicates the major version number, and /// the value mod 10 is the minor version number /// - public int VersionMadeBy - { - get - { - return (versionMadeBy & 0xff); - } - } + public int VersionMadeBy => versionMadeBy & 0xff; /// /// Get a value indicating this entry is for a DOS/Windows system. /// public bool IsDOSEntry - { - get - { - return ((HostSystem == (int)HostSystemID.Msdos) || - (HostSystem == (int)HostSystemID.WindowsNT)); - } - } + => (HostSystem == (int)HostSystemID.Msdos) + || (HostSystem == (int)HostSystemID.WindowsNT); /// /// Test the external attributes for this to @@ -481,7 +403,7 @@ private bool HasDosAttributes(int attributes) } /// - /// Gets the compatability information for the external file attribute + /// Gets the compatibility information for the external file attribute /// If the external file attributes are compatible with MS-DOS and can be read /// by PKZIP for DOS version 2.04g then this value will be zero. Otherwise the value /// will be non-zero and identify the host system on which the attributes are compatible. @@ -519,10 +441,7 @@ private bool HasDosAttributes(int attributes) /// public int HostSystem { - get - { - return (versionMadeBy >> 8) & 0xff; - } + get => (versionMadeBy >> 8) & 0xff; set { @@ -567,42 +486,26 @@ public int Version { // Return recorded version if known. if (versionToExtract != 0) - { - return versionToExtract & 0x00ff; // Only lower order byte. High order is O/S file system. - } - else - { - int result = 10; - if (AESKeySize > 0) - { - result = ZipConstants.VERSION_AES; // Ver 5.1 = AES - } - else if (CentralHeaderRequiresZip64) - { - result = ZipConstants.VersionZip64; - } - else if (CompressionMethod.Deflated == method) - { - result = 20; - } - else if (CompressionMethod.BZip2 == method) - { - result = ZipConstants.VersionBZip2; - } - else if (IsDirectory == true) - { - result = 20; - } - else if (IsCrypted == true) - { - result = 20; - } - else if (HasDosAttributes(0x08)) - { - result = 11; - } - return result; - } + // Only lower order byte. High order is O/S file system. + return versionToExtract & 0x00ff; + + if (AESKeySize > 0) + // Ver 5.1 = AES + return ZipConstants.VERSION_AES; + + if (CompressionMethod.BZip2 == method) + return ZipConstants.VersionBZip2; + + if (CentralHeaderRequiresZip64) + return ZipConstants.VersionZip64; + + if (CompressionMethod.Deflated == method || IsDirectory || IsCrypted) + return 20; + + if (HasDosAttributes(0x08)) + return 11; + + return 10; } } @@ -611,37 +514,21 @@ public int Version /// /// This is based on the and /// whether the compression method is supported. - public bool CanDecompress - { - get - { - return (Version <= ZipConstants.VersionMadeBy) && - ((Version == 10) || - (Version == 11) || - (Version == 20) || - (Version == 45) || - (Version == 46) || - (Version == 51)) && - IsCompressionMethodSupported(); - } - } + public bool CanDecompress + => Version <= ZipConstants.VersionMadeBy + && (Version == 10 || Version == 11 || Version == 20 || Version == 45 || Version == 46 || Version == 51) + && IsCompressionMethodSupported(); /// /// Force this entry to be recorded using Zip64 extensions. /// - public void ForceZip64() - { - forceZip64_ = true; - } + public void ForceZip64() => forceZip64_ = true; /// /// Get a value indicating whether Zip64 extensions were forced. /// /// A value of true if Zip64 extensions have been forced on; false if not. - public bool IsZip64Forced() - { - return forceZip64_; - } + public bool IsZip64Forced() => forceZip64_; /// /// Gets a value indicating if the entry requires Zip64 extensions @@ -677,13 +564,8 @@ public bool LocalHeaderRequiresZip64 /// /// Get a value indicating whether the central directory entry requires Zip64 extensions to be stored. /// - public bool CentralHeaderRequiresZip64 - { - get - { - return LocalHeaderRequiresZip64 || (offset >= uint.MaxValue); - } - } + public bool CentralHeaderRequiresZip64 + => LocalHeaderRequiresZip64 || (offset >= uint.MaxValue); /// /// Get/Set DosTime value. @@ -699,41 +581,39 @@ public long DosTime { return 0; } - else - { - var year = (uint)DateTime.Year; - var month = (uint)DateTime.Month; - var day = (uint)DateTime.Day; - var hour = (uint)DateTime.Hour; - var minute = (uint)DateTime.Minute; - var second = (uint)DateTime.Second; - - if (year < 1980) - { - year = 1980; - month = 1; - day = 1; - hour = 0; - minute = 0; - second = 0; - } - else if (year > 2107) - { - year = 2107; - month = 12; - day = 31; - hour = 23; - minute = 59; - second = 59; - } - return ((year - 1980) & 0x7f) << 25 | - (month << 21) | - (day << 16) | - (hour << 11) | - (minute << 5) | - (second >> 1); + var year = (uint)DateTime.Year; + var month = (uint)DateTime.Month; + var day = (uint)DateTime.Day; + var hour = (uint)DateTime.Hour; + var minute = (uint)DateTime.Minute; + var second = (uint)DateTime.Second; + + if (year < 1980) + { + year = 1980; + month = 1; + day = 1; + hour = 0; + minute = 0; + second = 0; } + else if (year > 2107) + { + year = 2107; + month = 12; + day = 31; + hour = 23; + minute = 59; + second = 59; + } + + return ((year - 1980) & 0x7f) << 25 | + (month << 21) | + (day << 16) | + (hour << 11) | + (minute << 5) | + (second >> 1); } set @@ -760,10 +640,7 @@ public long DosTime /// public DateTime DateTime { - get - { - return dateTime; - } + get => dateTime; set { @@ -783,15 +660,8 @@ public DateTime DateTime /// public string Name { - get - { - return name; - } - - internal set - { - name = value; - } + get => name; + internal set => name = value; } /// @@ -801,17 +671,14 @@ internal set /// The size or -1 if unknown. /// /// Setting the size before adding an entry to an archive can help - /// avoid compatability problems with some archivers which dont understand Zip64 extensions. + /// avoid compatibility problems with some archivers which don't understand Zip64 extensions. public long Size { - get - { - return (known & Known.Size) != 0 ? (long)size : -1L; - } + get => (known & Known.Size) != 0 ? (long)size : -1L; set { - this.size = (ulong)value; - this.known |= Known.Size; + size = (ulong)value; + known |= Known.Size; } } @@ -823,14 +690,11 @@ public long Size /// public long CompressedSize { - get - { - return (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L; - } + get => (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L; set { - this.compressedSize = (ulong)value; - this.known |= Known.CompressedSize; + compressedSize = (ulong)value; + known |= Known.CompressedSize; } } @@ -845,13 +709,10 @@ public long CompressedSize /// public long Crc { - get - { - return (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L; - } + get => (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L; set { - if (((ulong)crc & 0xffffffff00000000L) != 0) + if ((crc & 0xffffffff00000000L) != 0) { throw new ArgumentOutOfRangeException(nameof(value)); } @@ -861,28 +722,19 @@ public long Crc } /// - /// Gets/Sets the compression method. Only Deflated and Stored are supported. + /// Gets/Sets the compression method. /// + /// Throws exception when set if the method is not valid as per + /// /// /// The compression method for this entry /// - /// - /// public CompressionMethod CompressionMethod { - get - { - return method; - } - - set - { - if (!IsCompressionMethodSupported(value)) - { - throw new NotSupportedException("Compression method not supported"); - } - this.method = value; - } + get => method; + set => method = !IsCompressionMethodSupported(value) + ? throw new NotSupportedException("Compression method not supported") + : value; } /// @@ -890,13 +742,8 @@ public CompressionMethod CompressionMethod /// Returns same value as CompressionMethod except when AES encrypting, which /// places 99 in the method and places the real method in the extra data. /// - internal CompressionMethod CompressionMethodForHeader - { - get - { - return (AESKeySize > 0) ? CompressionMethod.WinZipAES : method; - } - } + internal CompressionMethod CompressionMethodForHeader + => (AESKeySize > 0) ? CompressionMethod.WinZipAES : method; /// /// Gets/Sets the extra data. @@ -909,12 +756,9 @@ internal CompressionMethod CompressionMethodForHeader /// public byte[] ExtraData { - get - { - // TODO: This is slightly safer but less efficient. Think about whether it should change. - // return (byte[]) extra.Clone(); - return extra; - } + // TODO: This is slightly safer but less efficient. Think about whether it should change. + // return (byte[]) extra.Clone(); + get => extra; set { @@ -986,62 +830,38 @@ public int AESKeySize /// AES Encryption strength for storage in extra data in entry header. /// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit. /// - internal byte AESEncryptionStrength - { - get - { - return (byte)_aesEncryptionStrength; - } - } + internal byte AESEncryptionStrength => (byte)_aesEncryptionStrength; /// /// Returns the length of the salt, in bytes /// - internal int AESSaltLen - { - get - { - // Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes. - return AESKeySize / 16; - } - } + /// Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes. + internal int AESSaltLen => AESKeySize / 16; /// /// Number of extra bytes required to hold the AES Header fields (Salt, Pwd verify, AuthCode) /// - internal int AESOverheadSize - { - get - { - // File format: - // Bytes Content - // Variable Salt value - // 2 Password verification value - // Variable Encrypted file data - // 10 Authentication code - return 12 + AESSaltLen; - } - } + /// File format: + /// Bytes | Content + /// ---------+--------------------------- + /// Variable | Salt value + /// 2 | Password verification value + /// Variable | Encrypted file data + /// 10 | Authentication code + internal int AESOverheadSize => 12 + AESSaltLen; /// /// Number of extra bytes required to hold the encryption header fields. /// - internal int EncryptionOverheadSize - { - get - { + internal int EncryptionOverheadSize => + !IsCrypted // Entry is not encrypted - no overhead - if (!this.IsCrypted) - return 0; - - // Entry is encrypted using ZipCrypto - if (_aesEncryptionStrength == 0) - return ZipConstants.CryptoHeaderSize; - - // Entry is encrypted using AES - return this.AESOverheadSize; - } - } + ? 0 + : _aesEncryptionStrength == 0 + // Entry is encrypted using ZipCrypto + ? ZipConstants.CryptoHeaderSize + // Entry is encrypted using AES + : AESOverheadSize; /// /// Process extra data fields updating the entry based on the contents. @@ -1144,7 +964,6 @@ internal void ProcessExtraData(bool localHeader) } // For AES the method in the entry is 99, and the real compression method is in the extradata - // private void ProcessAESExtraData(ZipExtraData extraData) { if (extraData.Find(0x9901)) @@ -1172,7 +991,7 @@ private void ProcessAESExtraData(ZipExtraData extraData) /// /// Gets/Sets the entry comment. /// - /// + /// /// If comment is longer than 0xffff. /// /// @@ -1180,14 +999,11 @@ private void ProcessAESExtraData(ZipExtraData extraData) /// /// /// A comment is only available for entries when read via the class. - /// The class doesnt have the comment data available. + /// The class doesn't have the comment data available. /// public string Comment { - get - { - return comment; - } + get => comment; set { // This test is strictly incorrect as the length is in characters @@ -1196,7 +1012,7 @@ public string Comment // is definitely invalid, shorter comments may also have an invalid length // where there are multi-byte characters // The full test is not possible here however as the code page to apply conversions with - // isnt available. + // isn't available. if ((value != null) && (value.Length > 0xffff)) { throw new ArgumentOutOfRangeException(nameof(value), "cannot exceed 65535"); @@ -1216,19 +1032,9 @@ public string Comment /// Currently only dos/windows attributes are tested in this manner. /// The trailing slash convention should always be followed. /// - public bool IsDirectory - { - get - { - int nameLength = name.Length; - bool result = - ((nameLength > 0) && - ((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) || - HasDosAttributes(16) - ; - return result; - } - } + public bool IsDirectory + => name.Length > 0 + && (name[name.Length - 1] == '/' || name[name.Length - 1] == '\\') || HasDosAttributes(16); /// /// Get a value of true if the entry appears to be a file; false otherwise @@ -1237,22 +1043,13 @@ public bool IsDirectory /// This only takes account of DOS/Windows attributes. Other operating systems are ignored. /// For linux and others the result may be incorrect. /// - public bool IsFile - { - get - { - return !IsDirectory && !HasDosAttributes(8); - } - } + public bool IsFile => !IsDirectory && !HasDosAttributes(8); /// /// Test entry to see if data can be extracted. /// /// Returns true if data can be extracted for this entry; false otherwise. - public bool IsCompressionMethodSupported() - { - return IsCompressionMethodSupported(CompressionMethod); - } + public bool IsCompressionMethodSupported() => IsCompressionMethodSupported(CompressionMethod); #region ICloneable Members @@ -1280,10 +1077,7 @@ public object Clone() /// Gets a string representation of this ZipEntry. /// /// A readable textual representation of this - public override string ToString() - { - return name; - } + public override string ToString() => name; /// /// Test a compression method to see if this library @@ -1291,13 +1085,10 @@ public override string ToString() /// /// The compression method to test. /// Returns true if the compression method is supported; false otherwise - public static bool IsCompressionMethodSupported(CompressionMethod method) - { - return - (method == CompressionMethod.Deflated) || - (method == CompressionMethod.Stored) || - (method == CompressionMethod.BZip2); - } + public static bool IsCompressionMethodSupported(CompressionMethod method) + => method == CompressionMethod.Deflated + || method == CompressionMethod.Stored + || method == CompressionMethod.BZip2; /// /// Cleans a name making it conform to Zip file conventions. diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntryExtensions.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryExtensions.cs new file mode 100644 index 000000000..927e94cfe --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryExtensions.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace ICSharpCode.SharpZipLib.Zip +{ + /// + /// General ZipEntry helper extensions + /// + public static class ZipEntryExtensions + { + /// + /// Efficiently check if a flag is set without enum un-/boxing + /// + /// + /// + /// Returns whether the flag was set + public static bool HasFlag(this ZipEntry entry, GeneralBitFlags flag) + => (entry.Flags & (int) flag) != 0; + + /// + /// Efficiently set a flag without enum un-/boxing + /// + /// + /// + /// Whether the passed flag should be set (1) or cleared (0) + public static void SetFlag(this ZipEntry entry, GeneralBitFlags flag, bool enabled = true) + => entry.Flags = enabled + ? entry.Flags | (int) flag + : entry.Flags & ~(int) flag; + } +} diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs index 66a3fc872..cccac6639 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs @@ -126,14 +126,15 @@ public string Password /// /// The entry can only be decompressed if the library supports the zip features required to extract it. /// See the ZipEntry Version property for more details. + /// + /// Since uses the local headers for extraction, entries with no compression combined with the + /// flag set, cannot be extracted as the end of the entry data cannot be deduced. /// - public bool CanDecompressEntry - { - get - { - return (entry != null) && IsEntryCompressionMethodSupported(entry) && entry.CanDecompress; - } - } + public bool CanDecompressEntry + => entry != null + && IsEntryCompressionMethodSupported(entry) + && entry.CanDecompress + && (!entry.HasFlag(GeneralBitFlags.Descriptor) || entry.CompressionMethod != CompressionMethod.Stored || entry.IsCrypted); /// /// Is the compression method for the specified entry supported? @@ -142,7 +143,7 @@ public bool CanDecompressEntry /// Uses entry.CompressionMethodForHeader so that entries of type WinZipAES will be rejected. /// /// the entry to check. - /// true if the compression methiod is supported, false if not. + /// true if the compression method is supported, false if not. private static bool IsEntryCompressionMethodSupported(ZipEntry entry) { var entryCompressionMethod = entry.CompressionMethodForHeader; @@ -493,6 +494,14 @@ private int ReadingNotSupported(byte[] destination, int offset, int count) throw new ZipException("The compression method for this entry is not supported"); } + /// + /// Handle attempts to read from this entry by throwing an exception + /// + private int StoredDescriptorEntry(byte[] destination, int offset, int count) => + throw new StreamUnsupportedException( + "The combination of Stored compression method and Descriptor flag is not possible to read using ZipInputStream"); + + /// /// Perform the initial read on an entry which may include /// reading encryption headers and setting up inflation. @@ -503,10 +512,7 @@ private int ReadingNotSupported(byte[] destination, int offset, int count) /// The actual number of bytes read. private int InitialRead(byte[] destination, int offset, int count) { - if (!CanDecompressEntry) - { - throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version + ")"); - } + var usesDescriptor = (entry.Flags & (int)GeneralBitFlags.Descriptor) != 0; // Handle encryption if required. if (entry.IsCrypted) @@ -534,9 +540,9 @@ private int InitialRead(byte[] destination, int offset, int count) { csize -= ZipConstants.CryptoHeaderSize; } - else if ((entry.Flags & (int)GeneralBitFlags.Descriptor) == 0) + else if (!usesDescriptor) { - throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize)); + throw new ZipException($"Entry compressed size {csize} too small for encryption"); } } else @@ -544,21 +550,33 @@ private int InitialRead(byte[] destination, int offset, int count) inputBuffer.CryptoTransform = null; } - if ((csize > 0) || ((flags & (int)GeneralBitFlags.Descriptor) != 0)) + if (csize > 0 || usesDescriptor) { - if ((method == CompressionMethod.Deflated) && (inputBuffer.Available > 0)) + if (method == CompressionMethod.Deflated && inputBuffer.Available > 0) { inputBuffer.SetInflaterInput(inf); } - internalReader = new ReadDataHandler(BodyRead); + // It's not possible to know how many bytes to read when using "Stored" compression (unless using encryption) + if (!entry.IsCrypted && method == CompressionMethod.Stored && usesDescriptor) + { + internalReader = StoredDescriptorEntry; + return StoredDescriptorEntry(destination, offset, count); + } + + if (!CanDecompressEntry) + { + internalReader = ReadingNotSupported; + return ReadingNotSupported(destination, offset, count); + } + + internalReader = BodyRead; return BodyRead(destination, offset, count); } - else - { - internalReader = new ReadDataHandler(ReadingNotAvailable); - return 0; - } + + + internalReader = ReadingNotAvailable; + return 0; } /// diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 8be25a4dc..19da3adf6 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -227,20 +227,14 @@ public void Encryption(ZipEncryptionMethod encryptionMethod) [Category("Zip")] public void CreateExceptions() { - var fastZip = new FastZip(); - string tempFilePath = GetTempFilePath(); - Assert.IsNotNull(tempFilePath, "No permission to execute this test?"); - Assert.Throws(() => { - string addFile = Path.Combine(tempFilePath, "test.zip"); - try - { - fastZip.CreateZip(addFile, @"z:\doesnt exist", false, null); - } - finally + using (var tempDir = new Utils.TempDir()) { - File.Delete(addFile); + var fastZip = new FastZip(); + var badPath = Path.Combine(Path.GetTempPath(), Utils.GetDummyFileName()); + var addFile = Path.Combine(tempDir.Fullpath, "test.zip"); + fastZip.CreateZip(addFile, badPath, false, null); } }); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index 60d7a5709..7a336592a 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -520,5 +520,41 @@ public void AddingAnAESEntryWithNoPasswordShouldThrow() } } } + + [Test] + [Category("Zip")] + public void ShouldThrowDescriptiveExceptionOnUncompressedDescriptorEntry() + { + using (var ms = new MemoryStreamWithoutSeek()) + { + using (var zos = new ZipOutputStream(ms)) + { + zos.IsStreamOwner = false; + var entry = new ZipEntry("testentry"); + entry.CompressionMethod = CompressionMethod.Stored; + entry.Flags |= (int)GeneralBitFlags.Descriptor; + zos.PutNextEntry(entry); + zos.Write(new byte[1], 0, 1); + zos.CloseEntry(); + } + + // Patch the Compression Method, since ZipOutputStream automatically changes it to Deflate when descriptors are used + ms.Seek(8, SeekOrigin.Begin); + ms.WriteByte((byte)CompressionMethod.Stored); + ms.Seek(0, SeekOrigin.Begin); + + using (var zis = new ZipInputStream(ms)) + { + zis.IsStreamOwner = false; + var buf = new byte[32]; + zis.GetNextEntry(); + + Assert.Throws(typeof(StreamUnsupportedException), () => + { + zis.Read(buf, 0, buf.Length); + }); + } + } + } } } From f9bd53dc97e1c68aec28d236806cfe5ecf163bb7 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 7 Mar 2021 15:45:43 +0000 Subject: [PATCH 083/162] PR #588: Add a simple async read test for ZipFile --- .../Zip/ZipFileHandling.cs | 24 +++++++++++ .../Zip/ZipTests.cs | 43 ++++++++++++++++++- 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index c92dae280..9d50fb844 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -5,6 +5,7 @@ using System; using System.IO; using System.Text; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -582,6 +583,29 @@ public void RoundTripInMemory() } } + /// + /// Simple async round trip test for ZipFile class + /// + [TestCase(CompressionMethod.Stored)] + [TestCase(CompressionMethod.Deflated)] + [TestCase(CompressionMethod.BZip2)] + [Category("Zip")] + [Category("Async")] + public async Task RoundTripInMemoryAsync(CompressionMethod compressionMethod) + { + var storage = new MemoryStream(); + MakeZipFile(storage, compressionMethod, false, "", 10, 1024, ""); + + using (ZipFile zipFile = new ZipFile(storage)) + { + foreach (ZipEntry e in zipFile) + { + Stream instream = zipFile.GetInputStream(e); + await CheckKnownEntryAsync(instream, 1024); + } + } + } + [Test] [Category("Zip")] public void AddToEmptyArchive() diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipTests.cs index eff2e007b..4a0c9954f 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipTests.cs @@ -7,6 +7,7 @@ using System.IO; using System.Security; using System.Text; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -288,7 +289,7 @@ protected static byte ScatterValue(byte rhs) return (byte)((rhs * 253 + 7) & 0xff); } - private static void AddKnownDataToEntry(ZipOutputStream zipStream, int size) + private static void AddKnownDataToEntry(Stream zipStream, int size) { if (size > 0) { @@ -387,6 +388,27 @@ protected void MakeZipFile(Stream storage, bool isOwner, } } + protected void MakeZipFile(Stream storage, CompressionMethod compressionMethod, bool isOwner, + string entryNamePrefix, int entries, int size, string comment) + { + using (ZipFile f = new ZipFile(storage, leaveOpen: !isOwner)) + { + f.BeginUpdate(); + f.SetComment(comment); + + for (int i = 0; i < entries; ++i) + { + var data = new MemoryStream(); + AddKnownDataToEntry(data, size); + + var m = new MemoryDataSource(data.ToArray()); + f.Add(m, entryNamePrefix + (i + 1), compressionMethod); + } + + f.CommitUpdate(); + } + } + #endregion MakeZipFile Entries protected static void CheckKnownEntry(Stream inStream, int expectedCount) @@ -408,6 +430,25 @@ protected static void CheckKnownEntry(Stream inStream, int expectedCount) Assert.AreEqual(expectedCount, total, "Wrong number of bytes read from entry"); } + protected static async Task CheckKnownEntryAsync(Stream inStream, int expectedCount) + { + byte[] buffer = new byte[1024]; + + int bytesRead; + int total = 0; + byte nextValue = 0; + while ((bytesRead = await inStream.ReadAsync(buffer, 0, buffer.Length)) > 0) + { + total += bytesRead; + for (int i = 0; i < bytesRead; ++i) + { + Assert.AreEqual(nextValue, buffer[i], "Wrong value read from entry"); + nextValue = ScatterValue(nextValue); + } + } + Assert.AreEqual(expectedCount, total, "Wrong number of bytes read from entry"); + } + protected byte ReadByteChecked(Stream stream) { int rawValue = stream.ReadByte(); From c959373311ee4cf5be9cf79aaa3486c69dfcc5fb Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 7 Mar 2021 15:46:19 +0000 Subject: [PATCH 084/162] PR #586: Convert VB sample projects to PackageReference format --- .../vb/CreateZipFile/CreateZipFile.vbproj | 10 +++++----- .../vb/CreateZipFile/packages.config | 4 ---- .../vb/WpfCreateZipFile/WpfCreateZipFile.vbproj | 16 ++++++++-------- .../vb/WpfCreateZipFile/packages.config | 5 ----- .../vb/minibzip2/minibzip2.vbproj | 10 +++++----- .../vb/minibzip2/packages.config | 4 ---- .../vb/viewzipfile/packages.config | 4 ---- .../vb/viewzipfile/viewzipfile.vbproj | 10 +++++----- .../vb/zipfiletest/packages.config | 4 ---- .../vb/zipfiletest/zipfiletest.vbproj | 10 +++++----- 10 files changed, 28 insertions(+), 49 deletions(-) delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config delete mode 100644 samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj index c20cdae13..2057acd9f 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj @@ -66,9 +66,6 @@ false - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -95,9 +92,12 @@ - - + + + 1.3.1 + + False diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj index 5d882b23d..e6ccebddc 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj @@ -73,9 +73,6 @@ My Project\app.manifest - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -91,10 +88,6 @@ - - ..\..\packages\WPFFolderBrowser.1.0.2\lib\WPFFolderBrowser.dll - True - @@ -165,7 +158,6 @@ Settings.Designer.vb - @@ -177,5 +169,13 @@ false + + + 1.3.1 + + + 1.0.2 + + \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config deleted file mode 100644 index 1380bfc2b..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/packages.config +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj index 9c2dfd7e2..618adb8ad 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj @@ -74,9 +74,6 @@ My Project\app.manifest - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -113,7 +110,11 @@ Resources.Designer.vb - + + + 1.3.1 + + False @@ -124,7 +125,6 @@ - diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj index a7e5259e5..429d77bfc 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj @@ -66,9 +66,6 @@ false - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -91,7 +88,11 @@ Designer - + + + 1.3.1 + + False @@ -101,7 +102,6 @@ - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config deleted file mode 100644 index a938c1f99..000000000 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj index 4a53b5a64..ddde8318d 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj @@ -76,9 +76,6 @@ 42353,42354,42355 - - ..\..\packages\SharpZipLib.1.3.0\lib\net45\ICSharpCode.SharpZipLib.dll - @@ -101,7 +98,11 @@ Designer - + + + 1.3.1 + + False @@ -111,7 +112,6 @@ - \ No newline at end of file From 765eb69eed7e7dbbdb709fbc7739c697f091918d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 7 Mar 2021 16:50:59 +0100 Subject: [PATCH 085/162] PR #583: Restore entry times on FastZip extract * FastZip - fix TimeSetting control when extracting Zip entries * Add tests for FastZip file times Co-authored-by: va4es2 ref #555 #566 --- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 92 ++++++++- .../Zip/IEntryFactory.cs | 13 ++ .../Zip/ZipEntryFactory.cs | 2 +- .../Zip/FastZipHandling.cs | 175 ++++++++++++++++++ 4 files changed, 279 insertions(+), 3 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 348527e4f..01725f4c3 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -3,6 +3,7 @@ using System; using System.IO; using static ICSharpCode.SharpZipLib.Zip.Compression.Deflater; +using static ICSharpCode.SharpZipLib.Zip.ZipEntryFactory; namespace ICSharpCode.SharpZipLib.Zip { @@ -195,6 +196,29 @@ public FastZip() { } + /// + /// Initialise a new instance of using the specified + /// + /// The time setting to use when creating or extracting Zip entries. + /// Using TimeSetting.LastAccessTime[Utc] when + /// creating an archive will set the file time to the moment of reading. + /// + public FastZip(TimeSetting timeSetting) + { + entryFactory_ = new ZipEntryFactory(timeSetting); + restoreDateTimeOnExtract_ = true; + } + + /// + /// Initialise a new instance of using the specified + /// + /// The time to set all values for created or extracted Zip Entries. + public FastZip(DateTime time) + { + entryFactory_ = new ZipEntryFactory(time); + restoreDateTimeOnExtract_ = true; + } + /// /// Initialise a new instance of /// @@ -735,7 +759,39 @@ private void ExtractFileEntry(ZipEntry entry, string targetName) if (restoreDateTimeOnExtract_) { - File.SetLastWriteTime(targetName, entry.DateTime); + switch (entryFactory_.Setting) + { + case TimeSetting.CreateTime: + File.SetCreationTime(targetName, entry.DateTime); + break; + + case TimeSetting.CreateTimeUtc: + File.SetCreationTimeUtc(targetName, entry.DateTime); + break; + + case TimeSetting.LastAccessTime: + File.SetLastAccessTime(targetName, entry.DateTime); + break; + + case TimeSetting.LastAccessTimeUtc: + File.SetLastAccessTimeUtc(targetName, entry.DateTime); + break; + + case TimeSetting.LastWriteTime: + File.SetLastWriteTime(targetName, entry.DateTime); + break; + + case TimeSetting.LastWriteTimeUtc: + File.SetLastWriteTimeUtc(targetName, entry.DateTime); + break; + + case TimeSetting.Fixed: + File.SetLastWriteTime(targetName, entryFactory_.FixedDateTime); + break; + + default: + throw new ZipException("Unhandled time setting in ExtractFileEntry"); + } } if (RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) @@ -809,7 +865,39 @@ private void ExtractEntry(ZipEntry entry) Directory.CreateDirectory(dirName); if (entry.IsDirectory && restoreDateTimeOnExtract_) { - Directory.SetLastWriteTime(dirName, entry.DateTime); + switch (entryFactory_.Setting) + { + case TimeSetting.CreateTime: + Directory.SetCreationTime(dirName, entry.DateTime); + break; + + case TimeSetting.CreateTimeUtc: + Directory.SetCreationTimeUtc(dirName, entry.DateTime); + break; + + case TimeSetting.LastAccessTime: + Directory.SetLastAccessTime(dirName, entry.DateTime); + break; + + case TimeSetting.LastAccessTimeUtc: + Directory.SetLastAccessTimeUtc(dirName, entry.DateTime); + break; + + case TimeSetting.LastWriteTime: + Directory.SetLastWriteTime(dirName, entry.DateTime); + break; + + case TimeSetting.LastWriteTimeUtc: + Directory.SetLastWriteTimeUtc(dirName, entry.DateTime); + break; + + case TimeSetting.Fixed: + Directory.SetLastWriteTime(dirName, entryFactory_.FixedDateTime); + break; + + default: + throw new ZipException("Unhandled time setting in ExtractEntry"); + } } } else diff --git a/src/ICSharpCode.SharpZipLib/Zip/IEntryFactory.cs b/src/ICSharpCode.SharpZipLib/Zip/IEntryFactory.cs index bbe40c4d7..d7ec18140 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/IEntryFactory.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/IEntryFactory.cs @@ -1,4 +1,6 @@ +using System; using ICSharpCode.SharpZipLib.Core; +using static ICSharpCode.SharpZipLib.Zip.ZipEntryFactory; namespace ICSharpCode.SharpZipLib.Zip { @@ -50,5 +52,16 @@ public interface IEntryFactory /// Get/set the applicable. /// INameTransform NameTransform { get; set; } + + /// + /// Get the in use. + /// + TimeSetting Setting { get; } + + /// + /// Get the value to use when is set to , + /// or if not specified, the value of when the class was the initialized + /// + DateTime FixedDateTime { get; } } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs index e82eafc48..1e40baaff 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs @@ -364,7 +364,7 @@ public ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem) private INameTransform nameTransform_; private DateTime fixedDateTime_ = DateTime.Now; - private TimeSetting timeSetting_; + private TimeSetting timeSetting_ = TimeSetting.LastWriteTime; private bool isUnicodeText_; private int getAttributes_ = -1; diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 19da3adf6..d394f309c 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Text; +using TimeSetting = ICSharpCode.SharpZipLib.Zip.ZipEntryFactory.TimeSetting; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -685,5 +686,179 @@ public void CreateZipShouldLeaveOutputStreamOpenIfRequested(bool leaveOpen) } } } + + [Category("Zip")] + [Category("CreatesTempFile")] + [Test] + public void CreateZipShouldSetTimeOnEntriesFromConstructorDateTime() + { + var targetTime = TestTargetTime(TimeSetting.Fixed); + var fastZip = new FastZip(targetTime); + var target = CreateFastZipTestArchiveWithAnEntry(fastZip); + var archive = new MemoryStream(target.ToArray()); + using (var zf = new ZipFile(archive)) + { + Assert.AreEqual(targetTime, zf[0].DateTime); + } + } + + [Category("Zip")] + [Category("CreatesTempFile")] + [TestCase(TimeSetting.CreateTimeUtc), TestCase(TimeSetting.LastWriteTimeUtc), TestCase(TimeSetting.LastAccessTimeUtc)] + [TestCase(TimeSetting.CreateTime), TestCase(TimeSetting.LastWriteTime), TestCase(TimeSetting.LastAccessTime)] + public void CreateZipShouldSetTimeOnEntriesFromConstructorTimeSetting(TimeSetting timeSetting) + { + var targetTime = TestTargetTime(timeSetting); + var fastZip = new FastZip(timeSetting); + + var alterTime = (Action) null; + switch(timeSetting) + { + case TimeSetting.LastWriteTime: alterTime = fi => fi.LastWriteTime = targetTime; break; + case TimeSetting.LastWriteTimeUtc: alterTime = fi => fi.LastWriteTimeUtc = targetTime; break; + case TimeSetting.CreateTime: alterTime = fi => fi.CreationTime = targetTime; break; + case TimeSetting.CreateTimeUtc: alterTime = fi => fi.CreationTimeUtc = targetTime; break; + } + + var target = CreateFastZipTestArchiveWithAnEntry(fastZip, alterTime); + // Check that the file contents are correct in both cases + var archive = new MemoryStream(target.ToArray()); + using (var zf = new ZipFile(archive)) + { + Assert.AreEqual(TestTargetTime(timeSetting), zf[0].DateTime); + } + } + + [Category("Zip")] + [Category("CreatesTempFile")] + [TestCase(TimeSetting.CreateTimeUtc), TestCase(TimeSetting.LastWriteTimeUtc), TestCase(TimeSetting.LastAccessTimeUtc)] + [TestCase(TimeSetting.CreateTime), TestCase(TimeSetting.LastWriteTime), TestCase(TimeSetting.LastAccessTime)] + [TestCase(TimeSetting.Fixed)] + public void ExtractZipShouldSetTimeOnFilesFromConstructorTimeSetting(TimeSetting timeSetting) + { + var targetTime = ExpectedFixedTime(); + var archiveStream = CreateFastZipTestArchiveWithAnEntry(new FastZip(targetTime)); + + if (timeSetting == TimeSetting.Fixed) + { + Assert.Ignore("Fixed time without specifying a time is undefined"); + } + + var fastZip = new FastZip(timeSetting); + using (var extractDir = new Utils.TempDir()) + { + fastZip.ExtractZip(archiveStream, extractDir.Fullpath, FastZip.Overwrite.Always, + _ => true, "", "", true, true, false); + var fi = new FileInfo(Path.Combine(extractDir.Fullpath, SingleEntryFileName)); + Assert.AreEqual(targetTime, FileTimeFromTimeSetting(fi, timeSetting)); + } + } + + [Category("Zip")] + [Category("CreatesTempFile")] + [TestCase(DateTimeKind.Local), TestCase(DateTimeKind.Utc)] + public void ExtractZipShouldSetTimeOnFilesFromConstructorDateTime(DateTimeKind dtk) + { + // Create the archive with a fixed "bad" datetime + var target = CreateFastZipTestArchiveWithAnEntry(new FastZip(UnexpectedFixedTime(dtk))); + + // Extract the archive with a fixed time override + var targetTime = ExpectedFixedTime(dtk); + var fastZip = new FastZip(targetTime); + using (var extractDir = new Utils.TempDir()) + { + fastZip.ExtractZip(target, extractDir.Fullpath, FastZip.Overwrite.Always, + _ => true, "", "", true, true, false); + var fi = new FileInfo(Path.Combine(extractDir.Fullpath, SingleEntryFileName)); + var fileTime = FileTimeFromTimeSetting(fi, TimeSetting.Fixed); + if (fileTime.Kind != dtk) fileTime = fileTime.ToUniversalTime(); + Assert.AreEqual(targetTime, fileTime); + } + } + + [Category("Zip")] + [Category("CreatesTempFile")] + [TestCase(DateTimeKind.Local), TestCase(DateTimeKind.Utc)] + public void ExtractZipShouldSetTimeOnFilesWithEmptyConstructor(DateTimeKind dtk) + { + // Create the archive with a fixed datetime + var targetTime = ExpectedFixedTime(dtk); + var target = CreateFastZipTestArchiveWithAnEntry(new FastZip(targetTime)); + + // Extract the archive with an empty constructor + var fastZip = new FastZip(); + using (var extractDir = new Utils.TempDir()) + { + fastZip.ExtractZip(target, extractDir.Fullpath, FastZip.Overwrite.Always, + _ => true, "", "", true, true, false); + var fi = new FileInfo(Path.Combine(extractDir.Fullpath, SingleEntryFileName)); + Assert.AreEqual(targetTime, FileTimeFromTimeSetting(fi, TimeSetting.Fixed)); + } + } + + private static bool IsLastAccessTime(TimeSetting ts) + => ts == TimeSetting.LastAccessTime || ts == TimeSetting.LastAccessTimeUtc; + + private static DateTime FileTimeFromTimeSetting(FileInfo fi, TimeSetting timeSetting) + { + switch (timeSetting) + { + case TimeSetting.LastWriteTime: return fi.LastWriteTime; + case TimeSetting.LastWriteTimeUtc: return fi.LastWriteTimeUtc; + case TimeSetting.CreateTime: return fi.CreationTime; + case TimeSetting.CreateTimeUtc: return fi.CreationTimeUtc; + case TimeSetting.LastAccessTime: return fi.LastAccessTime; + case TimeSetting.LastAccessTimeUtc: return fi.LastAccessTimeUtc; + case TimeSetting.Fixed: return fi.LastWriteTime; + } + + throw new ArgumentException("Invalid TimeSetting", nameof(timeSetting)); + } + + private static DateTime TestTargetTime(TimeSetting ts) + { + var dtk = ts == TimeSetting.CreateTimeUtc + || ts == TimeSetting.LastWriteTimeUtc + || ts == TimeSetting.LastAccessTimeUtc + ? DateTimeKind.Utc + : DateTimeKind.Local; + + return IsLastAccessTime(ts) + // AccessTime will be altered by reading/writing the file entry + ? CurrentTime(dtk) + : ExpectedFixedTime(dtk); + } + + private static DateTime CurrentTime(DateTimeKind kind) + { + var now = kind == DateTimeKind.Utc ? DateTime.UtcNow : DateTime.Now; + return new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, (now.Second / 2) * 2, kind); + } + + private static DateTime ExpectedFixedTime(DateTimeKind dtk = DateTimeKind.Unspecified) + => new DateTime(2010, 5, 30, 16, 22, 50, dtk); + private static DateTime UnexpectedFixedTime(DateTimeKind dtk = DateTimeKind.Unspecified) + => new DateTime(1980, 10, 11, 22, 39, 30, dtk); + + private const string SingleEntryFileName = "testEntry.dat"; + + private static TrackedMemoryStream CreateFastZipTestArchiveWithAnEntry(FastZip fastZip, Action alterFile = null) + { + var target = new TrackedMemoryStream(); + + using (var tempFolder = new Utils.TempDir()) + { + + // Create test input file + var addFile = Path.Combine(tempFolder.Fullpath, SingleEntryFileName); + MakeTempFile(addFile, 16); + var fi = new FileInfo(addFile); + alterFile?.Invoke(fi); + + fastZip.CreateZip(target, tempFolder.Fullpath, false, SingleEntryFileName, null, leaveOpen: true); + } + + return target; + } } } From 1c1df7b4b563012d3999c53e26277bf42db6a403 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 7 Mar 2021 15:53:49 +0000 Subject: [PATCH 086/162] PR #575: Replace uses of new T[0] with Array.Empty * Add the 'EmptyRefs' helper, to support Array.Empty on .NET 4.5 (ref: #501) * Replace uses of 'new T[0]' with 'Empty.Array' --- src/ICSharpCode.SharpZipLib/Core/EmptyRefs.cs | 17 +++++++++++++++++ .../Encryption/ZipAESTransform.cs | 3 ++- src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs | 3 ++- src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs | 5 +++-- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 8 ++++---- .../Zip/ZipOutputStream.cs | 4 ++-- src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs | 5 +++-- 7 files changed, 33 insertions(+), 12 deletions(-) create mode 100644 src/ICSharpCode.SharpZipLib/Core/EmptyRefs.cs diff --git a/src/ICSharpCode.SharpZipLib/Core/EmptyRefs.cs b/src/ICSharpCode.SharpZipLib/Core/EmptyRefs.cs new file mode 100644 index 000000000..feb7a8e17 --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Core/EmptyRefs.cs @@ -0,0 +1,17 @@ +using System; + +namespace ICSharpCode.SharpZipLib.Core +{ + internal static class Empty + { +#if NET45 + internal static class EmptyArray + { + public static readonly T[] Value = new T[0]; + } + public static T[] Array() => EmptyArray.Value; +#else + public static T[] Array() => System.Array.Empty(); +#endif + } +} diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs index 437e25c10..5aced2d71 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs @@ -1,5 +1,6 @@ using System; using System.Security.Cryptography; +using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Encryption { @@ -163,7 +164,7 @@ public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int input { throw new NotImplementedException("TransformFinalBlock is not implemented and inputCount is greater than 0"); } - return new byte[0]; + return Empty.Array(); } /// diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs index 64a1e5e18..262c12ad3 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Text; +using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Tar { @@ -465,7 +466,7 @@ public TarEntry[] GetDirectoryEntries() { if ((file == null) || !Directory.Exists(file)) { - return new TarEntry[0]; + return Empty.Array(); } string[] list = Directory.GetFileSystemEntries(file); diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs index 0535b1250..4e075dc8d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Zip { @@ -521,7 +522,7 @@ public ZipExtraData(byte[] data) { if (data == null) { - _data = new byte[0]; + _data = Empty.Array(); } else { @@ -552,7 +553,7 @@ public void Clear() { if ((_data == null) || (_data.Length != 0)) { - _data = new byte[0]; + _data = Empty.Array(); } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 704911b3f..a99f1f5ba 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -539,7 +539,7 @@ public ZipFile(Stream stream, bool leaveOpen) } else { - entries_ = new ZipEntry[0]; + entries_ = Empty.Array(); isNewArchive_ = true; } } @@ -549,7 +549,7 @@ public ZipFile(Stream stream, bool leaveOpen) /// internal ZipFile() { - entries_ = new ZipEntry[0]; + entries_ = Empty.Array(); isNewArchive_ = true; } @@ -2338,7 +2338,7 @@ private int WriteCentralDirectoryHeader(ZipEntry entry) baseStream_.Write(centralExtraData, 0, centralExtraData.Length); } - byte[] rawComment = (entry.Comment != null) ? Encoding.ASCII.GetBytes(entry.Comment) : new byte[0]; + byte[] rawComment = (entry.Comment != null) ? Encoding.ASCII.GetBytes(entry.Comment) : Empty.Array(); if (rawComment.Length > 0) { @@ -3347,7 +3347,7 @@ private void DisposeInternal(bool disposing) if (!isDisposed_) { isDisposed_ = true; - entries_ = new ZipEntry[0]; + entries_ = Empty.Array(); if (IsStreamOwner && (baseStream_ != null)) { diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 3c49ec8cb..e2c0426fd 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -872,7 +872,7 @@ public override void Finish() byte[] entryComment = (entry.Comment != null) ? ZipStrings.ConvertToArray(entry.Flags, entry.Comment) : - new byte[0]; + Empty.Array(); if (entryComment.Length > 0xffff) { @@ -987,7 +987,7 @@ public override void Flush() /// /// Comment for the entire archive recorded in central header. /// - private byte[] zipComment = new byte[0]; + private byte[] zipComment = Empty.Array(); /// /// Flag indicating that header patching is required for the current entry. diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs index 6ef523b82..8c2447134 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs @@ -1,5 +1,6 @@ using System; using System.Text; +using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Zip { @@ -174,7 +175,7 @@ public static string ConvertToStringExt(int flags, byte[] data) /// Converted array public static byte[] ConvertToArray(string str) => str == null - ? new byte[0] + ? Empty.Array() : Encoding.GetEncoding(CodePage).GetBytes(str); /// @@ -187,7 +188,7 @@ public static byte[] ConvertToArray(string str) /// Converted array public static byte[] ConvertToArray(int flags, string str) => (string.IsNullOrEmpty(str)) - ? new byte[0] + ? Empty.Array() : EncodingFromFlag(flags).GetBytes(str); } } From a4e4502d559506ad950f8a0a8b336674203d06e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 7 Mar 2021 22:53:51 +0100 Subject: [PATCH 087/162] Remove custom nuget config --- test/ICSharpCode.SharpZipLib.Tests/NuGet.config | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 test/ICSharpCode.SharpZipLib.Tests/NuGet.config diff --git a/test/ICSharpCode.SharpZipLib.Tests/NuGet.config b/test/ICSharpCode.SharpZipLib.Tests/NuGet.config deleted file mode 100644 index 7be9c71ec..000000000 --- a/test/ICSharpCode.SharpZipLib.Tests/NuGet.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - From 5c4e4d36fe99dc4dc85c353e0a7da38e4d8154de Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 7 Mar 2021 22:08:48 +0000 Subject: [PATCH 088/162] PR #594: Remove the local nuget.config files from the test projects --- test/ICSharpCode.SharpZipLib.TestBootstrapper/NuGet.config | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 test/ICSharpCode.SharpZipLib.TestBootstrapper/NuGet.config diff --git a/test/ICSharpCode.SharpZipLib.TestBootstrapper/NuGet.config b/test/ICSharpCode.SharpZipLib.TestBootstrapper/NuGet.config deleted file mode 100644 index 7be9c71ec..000000000 --- a/test/ICSharpCode.SharpZipLib.TestBootstrapper/NuGet.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - From 00c673e6dd389b8a8b3f3a5943e0caa92df24837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 14 Mar 2021 14:23:10 +0100 Subject: [PATCH 089/162] PR #599: Use net46 as CI target framework for windows tests * use net46 for windows testing on push * use net46 for windows testing for PRs --- .github/workflows/on-push.yml | 4 ++-- .github/workflows/pull-request.yml | 14 +++----------- 2 files changed, 5 insertions(+), 13 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 1ef2bafad..547db929e 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -22,11 +22,11 @@ jobs: - configuration: debug os: windows libtarget: net45 - testtarget: net45 + testtarget: net46 - configuration: release os: windows libtarget: net45 - testtarget: net45 + testtarget: net46 steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index ede297174..d7dbbe75e 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -13,11 +13,7 @@ jobs: os: [ubuntu, windows, macos] target: [netstandard2.0, netstandard2.1] include: - - configuration: Debug - os: windows - target: net45 - - configuration: Release - os: windows + - os: windows target: net45 steps: - uses: actions/checkout@v2 @@ -41,12 +37,8 @@ jobs: os: [ubuntu, windows, macos] target: [netcoreapp3.1] include: - - configuration: debug - os: windows - target: net45 - - configuration: release - os: windows - target: net45 + - os: windows + target: net46 steps: - uses: actions/checkout@v2 From 5ae4f10f564f9459dfbf43fca5873340505c4a53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 14 Mar 2021 15:21:28 +0100 Subject: [PATCH 090/162] Split build and pack in CI on push --- .github/workflows/on-push.yml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 547db929e..9703afdb3 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -75,8 +75,15 @@ jobs: dotnet-version: '3.1.x' source-url: https://nuget.pkg.github.com/icsharpcode/index.json - - name: Build and pack - run: dotnet build -c Release -o dist /p:ContinuousIntegrationBuild=true /p:EmbedUntrackedSources=true /p:Version=$(git describe --abbrev | % { $_.substring(1) }) src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library for .NET Standard 2.0 + run: dotnet build -c Release -f netstandard2.0 /p:ContinuousIntegrationBuild=true src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library for .NET Standard 2.1 + run: dotnet build -c Release -f netstandard2.1 /p:ContinuousIntegrationBuild=true src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + - name: Build library for .NET Framework 4.5 + run: dotnet build -c Release -f net45 /p:ContinuousIntegrationBuild=true src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + + - name: Create nuget package + run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:ContinuousIntegrationBuild=true /p:EmbedUntrackedSources=true /p:Version=$(git describe --abbrev | % { $_.substring(1) }) - name: Upload nuget package artifact uses: actions/upload-artifact@v2 From 6e95ec221fe0c99d4cf6577153445f75c33c7d98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 14 Mar 2021 16:26:10 +0100 Subject: [PATCH 091/162] PR #601: pass tests that are within time tolerance --- test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index d394f309c..541e57cd8 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -750,7 +750,9 @@ public void ExtractZipShouldSetTimeOnFilesFromConstructorTimeSetting(TimeSetting fastZip.ExtractZip(archiveStream, extractDir.Fullpath, FastZip.Overwrite.Always, _ => true, "", "", true, true, false); var fi = new FileInfo(Path.Combine(extractDir.Fullpath, SingleEntryFileName)); - Assert.AreEqual(targetTime, FileTimeFromTimeSetting(fi, timeSetting)); + var actualTime = FileTimeFromTimeSetting(fi, timeSetting); + // Assert that the time is within +/- 2s of the target time to allow for timing/rounding discrepancies + Assert.LessOrEqual(Math.Abs((targetTime - actualTime).TotalSeconds), 2); } } From 4cb58538f32bcc2f94f67712426694e835c43997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 14 Mar 2021 18:15:43 +0100 Subject: [PATCH 092/162] PR #602: Update test/coverage packages and push to codecov * update test/coverage packages and push to codecov * update bootstrapper packages * upload coverage on push --- .github/workflows/on-push.yml | 7 ++++++- .github/workflows/pull-request.yml | 7 ++++++- ...SharpCode.SharpZipLib.TestBootstrapper.csproj | 6 +++--- .../ICSharpCode.SharpZipLib.Tests.csproj | 16 ++++++++-------- 4 files changed, 23 insertions(+), 13 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 9703afdb3..1f6c3cad7 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -42,7 +42,12 @@ jobs: run: dotnet restore - name: Run tests - run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.testtarget }} --no-restore + run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.testtarget }} --no-restore --collect="XPlat Code Coverage" + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v1.2.2 + with: + fail_ci_if_error: false Codacy-Analysis: runs-on: ubuntu-latest diff --git a/.github/workflows/pull-request.yml b/.github/workflows/pull-request.yml index d7dbbe75e..85e91e8b2 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/pull-request.yml @@ -60,7 +60,12 @@ jobs: run: dotnet test -c debug -f ${{ matrix.target }} --no-restore - name: Run tests (Release) - run: dotnet test -c release -f ${{ matrix.target }} --no-restore + run: dotnet test -c release -f ${{ matrix.target }} --no-restore --collect="XPlat Code Coverage" + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v1.2.2 + with: + fail_ci_if_error: false Pack: needs: [Build, Test] diff --git a/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj b/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj index 0218e5d4d..3e3ba13d6 100644 --- a/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj +++ b/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj @@ -8,10 +8,10 @@ - + - - + + diff --git a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj index bf9e5b926..2c2a261d5 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj +++ b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj @@ -8,15 +8,15 @@ - - - - - - + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + - - From 7ed87d10b8ecafeb5abb5a129c046837416ac11f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 14 Mar 2021 18:34:45 +0100 Subject: [PATCH 093/162] PR #603: pass CreateZip tests that are within time tolerance --- test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 541e57cd8..9a6baac79 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -725,7 +725,10 @@ public void CreateZipShouldSetTimeOnEntriesFromConstructorTimeSetting(TimeSettin var archive = new MemoryStream(target.ToArray()); using (var zf = new ZipFile(archive)) { - Assert.AreEqual(TestTargetTime(timeSetting), zf[0].DateTime); + var expectedTime = TestTargetTime(timeSetting); + var actualTime = zf[0].DateTime; + // Assert that the time is within +/- 2s of the target time to allow for timing/rounding discrepancies + Assert.LessOrEqual(Math.Abs((expectedTime - actualTime).TotalSeconds), 2); } } From 87ffb39a29599a8685f6179b16faf372b590d209 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Mon, 26 Apr 2021 15:37:56 +0200 Subject: [PATCH 094/162] chore(ci): only export coverage for release --- .github/workflows/on-push.yml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml index 1f6c3cad7..3f34273d5 100644 --- a/.github/workflows/on-push.yml +++ b/.github/workflows/on-push.yml @@ -40,9 +40,14 @@ jobs: - name: Restore test dependencies run: dotnet restore - - - name: Run tests - run: dotnet test -c ${{ matrix.configuration }} -f ${{ matrix.testtarget }} --no-restore --collect="XPlat Code Coverage" + + - name: Run tests (Debug) + if: ${{ matrix.configuration == 'debug' }} + run: dotnet test -c debug -f ${{ matrix.testtarget }} --no-restore + + - name: Run tests (Release) + if: ${{ matrix.configuration == 'release' }} + run: dotnet test -c release -f ${{ matrix.testtarget }} --no-restore --collect="XPlat Code Coverage" - name: Upload coverage to Codecov uses: codecov/codecov-action@v1.2.2 From 95b353f1e5460500db55c786ccd16468c25a7dc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 27 Apr 2021 09:13:58 +0200 Subject: [PATCH 095/162] test: retry zipcrypto password tests once (#614) This is due to the password check only comparing a single byte (as per the spec), which have a 1/255 chance of actually matching regardless of password. --- test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs index b74ed1ddc..e2c2072c6 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs @@ -147,9 +147,11 @@ public void UnsupportedCompressionMethod() /// /// Invalid passwords should be detected early if possible, seekable stream + /// Note: Have a 1/255 chance of failing due to CRC collision (hence retried once) /// [Test] [Category("Zip")] + [Retry(2)] public void InvalidPasswordSeekable() { byte[] originalData = null; @@ -216,9 +218,11 @@ public void ExerciseGetNextEntry() /// /// Invalid passwords should be detected early if possible, non seekable stream + /// Note: Have a 1/255 chance of failing due to CRC collision (hence retried once) /// [Test] [Category("Zip")] + [Retry(2)] public void InvalidPasswordNonSeekable() { byte[] originalData = null; From 1493f69a3328929f3d845898a3321ff042a49ab2 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Tue, 27 Apr 2021 20:12:36 +0100 Subject: [PATCH 096/162] PR #605: Suppress CA1707 warnings in the Constants classes --- src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs | 1 + src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterConstants.cs | 1 + src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs | 1 + 3 files changed, 3 insertions(+) diff --git a/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs b/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs index 422cd97a4..6930f113d 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs @@ -3,6 +3,7 @@ namespace ICSharpCode.SharpZipLib.GZip /// /// This class contains constants used for gzip. /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "kept for backwards compatibility")] sealed public class GZipConstants { /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterConstants.cs index b6d7f291b..b7c7d2a69 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/DeflaterConstants.cs @@ -5,6 +5,7 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression /// /// This class contains constants used for deflation. /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "kept for backwards compatibility")] public static class DeflaterConstants { /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs index b0f33a764..eadf33901 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs @@ -237,6 +237,7 @@ public enum GeneralBitFlags /// /// This class contains constants used for Zip format files /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1707:Identifiers should not contain underscores", Justification = "kept for backwards compatibility")] public static class ZipConstants { #region Versions From 8ab21b0a4df1081608a44065cdbc10f96e2b6c8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 27 Apr 2021 21:13:30 +0200 Subject: [PATCH 097/162] PR #593: Simplify DropPathRoot and fix out of bounds issue * Simplify DropPathRoot and fix out of bounds issue * prevent throwing in DropPathRoot and add tests * make path tests platform-specific testing for UNC paths on *nix does not really make sense * handle .NET < 4.6.2 special cases --- src/ICSharpCode.SharpZipLib/Core/PathUtils.cs | 58 +++++----------- .../Core/CoreTests.cs | 47 +++++++++++++ .../TestSupport/SevenZip.cs | 17 ++++- .../TestSupport/Utils.cs | 7 ++ .../Zip/ZipFileHandling.cs | 9 ++- .../Zip/ZipNameTransformHandling.cs | 66 ++++++++++++------- 6 files changed, 135 insertions(+), 69 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs b/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs index 2d6121786..77c4b07fc 100644 --- a/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs +++ b/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs @@ -1,4 +1,6 @@ +using System; using System.IO; +using System.Linq; namespace ICSharpCode.SharpZipLib.Core { @@ -12,51 +14,21 @@ public static class PathUtils /// /// A containing path information. /// The path with the root removed if it was present; path otherwise. - /// Unlike the class the path isn't otherwise checked for validity. public static string DropPathRoot(string path) { - string result = path; - - if (!string.IsNullOrEmpty(path)) - { - if ((path[0] == '\\') || (path[0] == '/')) - { - // UNC name ? - if ((path.Length > 1) && ((path[1] == '\\') || (path[1] == '/'))) - { - int index = 2; - int elements = 2; - - // Scan for two separate elements \\machine\share\restofpath - while ((index <= path.Length) && - (((path[index] != '\\') && (path[index] != '/')) || (--elements > 0))) - { - index++; - } - - index++; - - if (index < path.Length) - { - result = path.Substring(index); - } - else - { - result = ""; - } - } - } - else if ((path.Length > 1) && (path[1] == ':')) - { - int dropCount = 2; - if ((path.Length > 2) && ((path[2] == '\\') || (path[2] == '/'))) - { - dropCount = 3; - } - result = result.Remove(0, dropCount); - } - } - return result; + var invalidChars = Path.GetInvalidPathChars(); + // If the first character after the root is a ':', .NET < 4.6.2 throws + var cleanRootSep = path.Length >= 3 && path[1] == ':' && path[2] == ':'; + + // Replace any invalid path characters with '_' to prevent Path.GetPathRoot from throwing. + // Only pass the first 258 (should be 260, but that still throws for some reason) characters + // as .NET < 4.6.2 throws on longer paths + var cleanPath = new string(path.Take(258) + .Select( (c, i) => invalidChars.Contains(c) || (i == 2 && cleanRootSep) ? '_' : c).ToArray()); + + var stripLength = Path.GetPathRoot(cleanPath).Length; + while (path.Length > stripLength && (path[stripLength] == '/' || path[stripLength] == '\\')) stripLength++; + return path.Substring(stripLength); } /// diff --git a/test/ICSharpCode.SharpZipLib.Tests/Core/CoreTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Core/CoreTests.cs index 985718fb2..1b43c79ae 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Core/CoreTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Core/CoreTests.cs @@ -1,3 +1,4 @@ +using System; using ICSharpCode.SharpZipLib.Core; using NUnit.Framework; @@ -54,5 +55,51 @@ public void ValidFilter() Assert.IsFalse(NameFilter.IsValidFilterExpression(@"\,)")); Assert.IsFalse(NameFilter.IsValidFilterExpression(@"[]")); } + + // Use a shorter name wrapper to make tests more legible + private static string DropRoot(string s) => PathUtils.DropPathRoot(s); + + [Test] + [Category("Core")] + [Platform("Win")] + public void DropPathRoot_Windows() + { + Assert.AreEqual("file.txt", DropRoot(@"\\server\share\file.txt")); + Assert.AreEqual("file.txt", DropRoot(@"c:\file.txt")); + Assert.AreEqual(@"subdir with spaces\file.txt", DropRoot(@"z:\subdir with spaces\file.txt")); + Assert.AreEqual("", DropRoot(@"\\server\share\")); + Assert.AreEqual(@"server\share\file.txt", DropRoot(@"\server\share\file.txt")); + Assert.AreEqual(@"path\file.txt", DropRoot(@"\\server\share\\path\file.txt")); + } + + [Test] + [Category("Core")] + [Platform(Exclude="Win")] + public void DropPathRoot_Posix() + { + Assert.AreEqual("file.txt", DropRoot("/file.txt")); + Assert.AreEqual(@"tmp/file.txt", DropRoot(@"/tmp/file.txt")); + Assert.AreEqual(@"tmp\file.txt", DropRoot(@"\tmp\file.txt")); + Assert.AreEqual(@"tmp/file.txt", DropRoot(@"\tmp/file.txt")); + Assert.AreEqual(@"tmp\file.txt", DropRoot(@"/tmp\file.txt")); + Assert.AreEqual("", DropRoot("/")); + + } + + [Test] + [TestCase(@"c:\file:+/")] + [TestCase(@"c:\file*?")] + [TestCase("c:\\file|\"")] + [TestCase(@"c:\file<>")] + [TestCase(@"c:file")] + [TestCase(@"c::file")] + [TestCase(@"c:?file")] + [TestCase(@"c:+file")] + [TestCase(@"cc:file")] + [Category("Core")] + public void DropPathRoot_DoesNotThrowForInvalidPath(string path) + { + Assert.DoesNotThrow(() => Console.WriteLine(PathUtils.DropPathRoot(path))); + } } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs index c312ec401..e9887172a 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/SevenZip.cs @@ -17,7 +17,7 @@ internal static class SevenZipHelper Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "7-Zip", "7z.exe"), }; - public static bool TryGet7zBinPath(out string path7z) + private static bool TryGet7zBinPath(out string path7z) { var runTimeLimit = TimeSpan.FromSeconds(3); @@ -77,12 +77,25 @@ internal static void VerifyZipWith7Zip(Stream zipStream, string password) zipStream.CopyTo(fs); } - var p = Process.Start(path7z, $"t -p{password} \"{fileName}\""); + var p = Process.Start(new ProcessStartInfo(path7z, $"t -p{password} \"{fileName}\"") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }); + + if (p == null) + { + Assert.Inconclusive("Failed to start 7z process. Skipping!"); + } if (!p.WaitForExit(2000)) { Assert.Warn("Timed out verifying zip file!"); } + TestContext.Out.Write(p.StandardOutput.ReadToEnd()); + var errors = p.StandardError.ReadToEnd(); + Assert.IsEmpty(errors, "7z reported errors"); Assert.AreEqual(0, p.ExitCode, "Archive verification failed"); } finally diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs index 9c582daa6..33d6e3e9b 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs @@ -13,9 +13,16 @@ public static class Utils public static int DummyContentLength = 16; private static Random random = new Random(); + + /// + /// Returns the system root for the current platform (usually c:\ for windows and / for others) + /// + public static string SystemRoot { get; } = + Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)); private static void Compare(byte[] a, byte[] b) { + if (a == null) { throw new ArgumentNullException(nameof(a)); diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index 9d50fb844..a9a7583fc 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -23,6 +23,7 @@ public void NullStreamDetected() try { + // ReSharper disable once ExpressionIsAlwaysNull bad = new ZipFile(nullStream); } catch @@ -439,17 +440,21 @@ public void AddAndDeleteEntriesMemory() f.IsStreamOwner = false; f.BeginUpdate(new MemoryArchiveStorage()); - f.Add(new StringMemoryDataSource("Hello world"), @"z:\a\a.dat"); + f.Add(new StringMemoryDataSource("Hello world"), Utils.SystemRoot + @"a\a.dat"); f.Add(new StringMemoryDataSource("Another"), @"\b\b.dat"); f.Add(new StringMemoryDataSource("Mr C"), @"c\c.dat"); f.Add(new StringMemoryDataSource("Mrs D was a star"), @"d\d.dat"); f.CommitUpdate(); Assert.IsTrue(f.TestArchive(true)); + foreach (ZipEntry entry in f) + { + Console.WriteLine($" - {entry.Name}"); + } } byte[] master = memStream.ToArray(); - TryDeleting(master, 4, 1, @"z:\a\a.dat"); + TryDeleting(master, 4, 1, Utils.SystemRoot + @"a\a.dat"); TryDeleting(master, 4, 1, @"\a\a.dat"); TryDeleting(master, 4, 1, @"a/a.dat"); diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs index 498a8f723..e51b8f19d 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs @@ -3,6 +3,7 @@ using NUnit.Framework; using System; using System.IO; +using ICSharpCode.SharpZipLib.Tests.TestSupport; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -16,8 +17,6 @@ public void Basic() var t = new ZipNameTransform(); TestFile(t, "abcdef", "abcdef"); - TestFile(t, @"\\uncpath\d1\file1", "file1"); - TestFile(t, @"C:\absolute\file2", "absolute/file2"); // This is ignored but could be converted to 'file3' TestFile(t, @"./file3", "./file3"); @@ -28,50 +27,73 @@ public void Basic() // Trick filenames. TestFile(t, @".....file3", ".....file3"); + } + + [Test] + [Category("Zip")] + [Platform("Win")] + public void Basic_Windows() + { + var t = new ZipNameTransform(); + TestFile(t, @"\\uncpath\d1\file1", "file1"); + TestFile(t, @"C:\absolute\file2", "absolute/file2"); + TestFile(t, @"c::file", "_file"); } + + [Test] + [Category("Zip")] + [Platform(Exclude="Win")] + public void Basic_Posix() + { + var t = new ZipNameTransform(); + TestFile(t, @"backslash_path\file1", "backslash_path/file1"); + TestFile(t, "/absolute/file2", "absolute/file2"); + + TestFile(t, @"////////:file", "_file"); + } [Test] public void TooLong() { var zt = new ZipNameTransform(); - var veryLong = new string('x', 65536); - try - { - zt.TransformDirectory(veryLong); - Assert.Fail("Expected an exception"); - } - catch (PathTooLongException) - { - } + var tooLong = new string('x', 65536); + Assert.Throws(() => zt.TransformDirectory(tooLong)); } [Test] public void LengthBoundaryOk() { var zt = new ZipNameTransform(); - string veryLong = "c:\\" + new string('x', 65535); - try - { - zt.TransformDirectory(veryLong); - } - catch - { - Assert.Fail("Expected no exception"); - } + var tooLongWithRoot = Utils.SystemRoot + new string('x', 65535); + Assert.DoesNotThrow(() => zt.TransformDirectory(tooLongWithRoot)); } [Test] [Category("Zip")] - public void NameTransforms() + [Platform("Win")] + public void NameTransforms_Windows() { INameTransform t = new ZipNameTransform(@"C:\Slippery"); Assert.AreEqual("Pongo/Directory/", t.TransformDirectory(@"C:\Slippery\Pongo\Directory"), "Value should be trimmed and converted"); Assert.AreEqual("PoNgo/Directory/", t.TransformDirectory(@"c:\slipperY\PoNgo\Directory"), "Trimming should be case insensitive"); - Assert.AreEqual("slippery/Pongo/Directory/", t.TransformDirectory(@"d:\slippery\Pongo\Directory"), "Trimming should be case insensitive"); + Assert.AreEqual("slippery/Pongo/Directory/", t.TransformDirectory(@"d:\slippery\Pongo\Directory"), "Trimming should account for root"); Assert.AreEqual("Pongo/File", t.TransformFile(@"C:\Slippery\Pongo\File"), "Value should be trimmed and converted"); } + + [Test] + [Category("Zip")] + [Platform(Exclude="Win")] + public void NameTransforms_Posix() + { + INameTransform t = new ZipNameTransform(@"/Slippery"); + Assert.AreEqual("Pongo/Directory/", t.TransformDirectory(@"/Slippery\Pongo\Directory"), "Value should be trimmed and converted"); + Assert.AreEqual("PoNgo/Directory/", t.TransformDirectory(@"/slipperY\PoNgo\Directory"), "Trimming should be case insensitive"); + Assert.AreEqual("slippery/Pongo/Directory/", t.TransformDirectory(@"/slippery/slippery/Pongo/Directory"), "Trimming should account for root"); + + Assert.AreEqual("Pongo/File", t.TransformFile(@"/Slippery/Pongo/File"), "Value should be trimmed and converted"); + } /// /// Test ZipEntry static file name cleaning methods From d9fb8a46f7735f17e8de5f5300006c0a144a9ecc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 27 Apr 2021 21:23:24 +0200 Subject: [PATCH 098/162] PR 351: Add support for Filename field in GZip --- .../GZip/GZipConstants.cs | 73 +++++++---- .../GZip/GzipInputStream.cs | 117 +++++++----------- .../GZip/GzipOutputStream.cs | 47 ++++++- .../Streams/InflaterInputStream.cs | 2 +- .../GZip/GZipTests.cs | 37 ++++++ 5 files changed, 171 insertions(+), 105 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs b/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs index 6930f113d..a59799278 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GZipConstants.cs @@ -1,3 +1,6 @@ +using System; +using System.Text; + namespace ICSharpCode.SharpZipLib.GZip { /// @@ -7,53 +10,69 @@ namespace ICSharpCode.SharpZipLib.GZip sealed public class GZipConstants { /// - /// Magic number found at start of GZIP header + /// First GZip identification byte /// - public const int GZIP_MAGIC = 0x1F8B; + public const byte ID1 = 0x1F; - /* The flag byte is divided into individual bits as follows: + /// + /// Second GZip identification byte + /// + public const byte ID2 = 0x8B; - bit 0 FTEXT - bit 1 FHCRC - bit 2 FEXTRA - bit 3 FNAME - bit 4 FCOMMENT - bit 5 reserved - bit 6 reserved - bit 7 reserved - */ + /// + /// Deflate compression method + /// + public const byte CompressionMethodDeflate = 0x8; /// - /// Flag bit mask for text + /// Get the GZip specified encoding (CP-1252 if supported, otherwise ASCII) /// - public const int FTEXT = 0x1; + public static Encoding Encoding + { + get + { + try + { + return Encoding.GetEncoding(1252); + } + catch + { + return Encoding.ASCII; + } + } + } + } + + /// + /// GZip header flags + /// + [Flags] + public enum GZipFlags: byte + { /// - /// Flag bitmask for Crc + /// Text flag hinting that the file is in ASCII /// - public const int FHCRC = 0x2; + FTEXT = 0x1 << 0, /// - /// Flag bit mask for extra + /// CRC flag indicating that a CRC16 preceeds the data /// - public const int FEXTRA = 0x4; + FHCRC = 0x1 << 1, /// - /// flag bitmask for name + /// Extra flag indicating that extra fields are present /// - public const int FNAME = 0x8; + FEXTRA = 0x1 << 2, /// - /// flag bit mask indicating comment is present + /// Filename flag indicating that the original filename is present /// - public const int FCOMMENT = 0x10; + FNAME = 0x1 << 3, /// - /// Initialise default instance. + /// Flag bit mask indicating that a comment is present /// - /// Constructor is private to prevent instances being created. - private GZipConstants() - { - } + FCOMMENT = 0x1 << 4, } } diff --git a/src/ICSharpCode.SharpZipLib/GZip/GzipInputStream.cs b/src/ICSharpCode.SharpZipLib/GZip/GzipInputStream.cs index a924a7ffc..20a4ded17 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GzipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GzipInputStream.cs @@ -3,6 +3,7 @@ using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using System; using System.IO; +using System.Text; namespace ICSharpCode.SharpZipLib.GZip { @@ -54,6 +55,8 @@ public class GZipInputStream : InflaterInputStream /// private bool completedLastBlock; + private string fileName; + #endregion Instance Fields #region Constructors @@ -149,6 +152,15 @@ public override int Read(byte[] buffer, int offset, int count) } } + /// + /// Retrieves the filename header field for the block last read + /// + /// + public string GetFilename() + { + return fileName; + } + #endregion Stream overrides #region Support routines @@ -170,132 +182,96 @@ private bool ReadHeader() } } - // 1. Check the two magic bytes var headCRC = new Crc32(); - int magic = inputBuffer.ReadLeByte(); - if (magic < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } + // 1. Check the two magic bytes + var magic = inputBuffer.ReadLeByte(); headCRC.Update(magic); - if (magic != (GZipConstants.GZIP_MAGIC >> 8)) + if (magic != GZipConstants.ID1) { throw new GZipException("Error GZIP header, first magic byte doesn't match"); } - //magic = baseInputStream.ReadByte(); magic = inputBuffer.ReadLeByte(); - - if (magic < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - if (magic != (GZipConstants.GZIP_MAGIC & 0xFF)) + if (magic != GZipConstants.ID2) { throw new GZipException("Error GZIP header, second magic byte doesn't match"); } - headCRC.Update(magic); // 2. Check the compression type (must be 8) - int compressionType = inputBuffer.ReadLeByte(); - - if (compressionType < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } + var compressionType = inputBuffer.ReadLeByte(); - if (compressionType != 8) + if (compressionType != GZipConstants.CompressionMethodDeflate) { throw new GZipException("Error GZIP header, data not in deflate format"); } headCRC.Update(compressionType); // 3. Check the flags - int flags = inputBuffer.ReadLeByte(); - if (flags < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(flags); - - /* This flag byte is divided into individual bits as follows: + var flagsByte = inputBuffer.ReadLeByte(); - bit 0 FTEXT - bit 1 FHCRC - bit 2 FEXTRA - bit 3 FNAME - bit 4 FCOMMENT - bit 5 reserved - bit 6 reserved - bit 7 reserved - */ + headCRC.Update(flagsByte); // 3.1 Check the reserved bits are zero - if ((flags & 0xE0) != 0) + if ((flagsByte & 0xE0) != 0) { throw new GZipException("Reserved flag bits in GZIP header != 0"); } + var flags = (GZipFlags)flagsByte; + // 4.-6. Skip the modification time, extra flags, and OS type for (int i = 0; i < 6; i++) { - int readByte = inputBuffer.ReadLeByte(); - if (readByte < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(readByte); + headCRC.Update(inputBuffer.ReadLeByte()); } // 7. Read extra field - if ((flags & GZipConstants.FEXTRA) != 0) + if (flags.HasFlag(GZipFlags.FEXTRA)) { // XLEN is total length of extra subfields, we will skip them all - int len1, len2; - len1 = inputBuffer.ReadLeByte(); - len2 = inputBuffer.ReadLeByte(); - if ((len1 < 0) || (len2 < 0)) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } + var len1 = inputBuffer.ReadLeByte(); + var len2 = inputBuffer.ReadLeByte(); + headCRC.Update(len1); headCRC.Update(len2); int extraLen = (len2 << 8) | len1; // gzip is LSB first for (int i = 0; i < extraLen; i++) { - int readByte = inputBuffer.ReadLeByte(); - if (readByte < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(readByte); + headCRC.Update(inputBuffer.ReadLeByte()); } } // 8. Read file name - if ((flags & GZipConstants.FNAME) != 0) + if (flags.HasFlag(GZipFlags.FNAME)) { + var fname = new byte[1024]; + var fnamePos = 0; int readByte; while ((readByte = inputBuffer.ReadLeByte()) > 0) { + if (fnamePos < 1024) + { + fname[fnamePos++] = (byte)readByte; + } headCRC.Update(readByte); } - if (readByte < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } headCRC.Update(readByte); + + fileName = GZipConstants.Encoding.GetString(fname, 0, fnamePos); + } + else + { + fileName = null; } // 9. Read comment - if ((flags & GZipConstants.FCOMMENT) != 0) + if (flags.HasFlag(GZipFlags.FCOMMENT)) { int readByte; while ((readByte = inputBuffer.ReadLeByte()) > 0) @@ -303,16 +279,11 @@ bit 7 reserved headCRC.Update(readByte); } - if (readByte < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(readByte); } // 10. Read header CRC - if ((flags & GZipConstants.FHCRC) != 0) + if (flags.HasFlag(GZipFlags.FHCRC)) { int tempByte; int crcval = inputBuffer.ReadLeByte(); diff --git a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs index afa43d7fd..31985f93b 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs @@ -3,6 +3,7 @@ using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using System; using System.IO; +using System.Text; namespace ICSharpCode.SharpZipLib.GZip { @@ -53,6 +54,10 @@ private enum OutputState private OutputState state_ = OutputState.Header; + private string fileName; + + private GZipFlags flags = 0; + #endregion Instance Fields #region Constructors @@ -111,6 +116,26 @@ public int GetLevel() return deflater_.GetLevel(); } + /// + /// Original filename + /// + public string FileName + { + get => fileName; + set + { + fileName = CleanFilename(value); + if (string.IsNullOrEmpty(fileName)) + { + flags &= ~GZipFlags.FNAME; + } + else + { + flags |= GZipFlags.FNAME; + } + } + } + #endregion Public API #region Stream overrides @@ -218,6 +243,9 @@ public override void Finish() #region Support Routines + private string CleanFilename(string path) + => path.Substring(path.LastIndexOf('/') + 1); + private void WriteHeader() { if (state_ == OutputState.Header) @@ -227,13 +255,14 @@ private void WriteHeader() var mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals byte[] gzipHeader = { // The two magic bytes - (byte) (GZipConstants.GZIP_MAGIC >> 8), (byte) (GZipConstants.GZIP_MAGIC & 0xff), + GZipConstants.ID1, + GZipConstants.ID2, // The compression type - (byte) Deflater.DEFLATED, + GZipConstants.CompressionMethodDeflate, // The flags (not set) - 0, + (byte)flags, // The modification time (byte) mod_time, (byte) (mod_time >> 8), @@ -243,9 +272,19 @@ private void WriteHeader() 0, // The OS type (unknown) - (byte) 255 + 255 }; + baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length); + + if (flags.HasFlag(GZipFlags.FNAME)) + { + var fname = GZipConstants.Encoding.GetBytes(fileName); + baseOutputStream_.Write(fname, 0, fname.Length); + + // End filename string with a \0 + baseOutputStream_.Write(new byte[] { 0 }, 0, 1); + } } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs index 3fb257906..7790474d2 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs @@ -226,7 +226,7 @@ public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length) /// Read a from the input stream. /// /// Returns the byte read. - public int ReadLeByte() + public byte ReadLeByte() { if (available <= 0) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs index 5846b0d5b..8a9f61d69 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs @@ -3,6 +3,7 @@ using NUnit.Framework; using System; using System.IO; +using System.Text; namespace ICSharpCode.SharpZipLib.Tests.GZip { @@ -514,5 +515,41 @@ public void ReadWriteThroughput() output: w => new GZipOutputStream(w) ); } + + /// + /// Basic compress/decompress test + /// + [Test] + [Category("GZip")] + public void OriginalFilename() + { + var content = "FileContents"; + + + using (var ms = new MemoryStream()) + { + using (var outStream = new GZipOutputStream(ms) { IsStreamOwner = false }) + { + outStream.FileName = "/path/to/file.ext"; + + var writeBuffer = Encoding.ASCII.GetBytes(content); + outStream.Write(writeBuffer, 0, writeBuffer.Length); + outStream.Flush(); + outStream.Finish(); + } + + ms.Seek(0, SeekOrigin.Begin); + + using (var inStream = new GZipInputStream(ms)) + { + var readBuffer = new byte[content.Length]; + inStream.Read(readBuffer, 0, readBuffer.Length); + Assert.AreEqual(content, Encoding.ASCII.GetString(readBuffer)); + Assert.AreEqual("file.ext", inStream.GetFilename()); + } + + } + + } } } From 5eea92acf228c72af124aa2fd7ca1b36987cdbbe Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Thu, 29 Apr 2021 12:16:44 +0100 Subject: [PATCH 099/162] PR #616: Change the build status badge to reference github actions --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 269cb048b..1a385d929 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# SharpZipLib [![Build status](https://ci.appveyor.com/api/projects/status/wuf8l79mypqsbor3/branch/master?svg=true)](https://ci.appveyor.com/project/icsharpcode/sharpziplib/branch/master) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) +# SharpZipLib [![Build Status](https://github.com/icsharpcode/SharpZipLib/actions/workflows/on-push.yml/badge.svg?branch=master)](https://github.com/icsharpcode/SharpZipLib/actions/workflows/on-push.yml) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) Introduction ------------ From 1b9fcfc6103074bb05fe76116d1adc2c999bb340 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Konrad=20Kruczy=C5=84ski?= Date: Tue, 4 May 2021 15:26:15 +0200 Subject: [PATCH 100/162] PR #611: Bzip input stream simple vectorization * Added benchmark for BZip2 decompression. * Updated benchmarks to be run also on .NET Core 3.1. * Simple automatic vectorization of the rotation loop. * Added comment describing vectorization. --- .../BZip2/BZip2InputStream.cs | 37 +++++++++++++++++++ .../ICSharpCode.SharpZipLib.Benchmark.csproj | 2 +- .../Program.cs | 2 +- .../BZip2/BZip2InputStream.cs | 27 ++++++++++++-- 4 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 benchmark/ICSharpCode.SharpZipLib.Benchmark/BZip2/BZip2InputStream.cs diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/BZip2/BZip2InputStream.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/BZip2/BZip2InputStream.cs new file mode 100644 index 000000000..8d5a7ccc2 --- /dev/null +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/BZip2/BZip2InputStream.cs @@ -0,0 +1,37 @@ +using System; +using System.IO; +using BenchmarkDotNet.Attributes; + +namespace ICSharpCode.SharpZipLib.Benchmark.BZip2 +{ + [Config(typeof(MultipleRuntimes))] + public class BZip2InputStream + { + private byte[] compressedData; + + public BZip2InputStream() + { + var outputMemoryStream = new MemoryStream(); + using (var outputStream = new SharpZipLib.BZip2.BZip2OutputStream(outputMemoryStream)) + { + var random = new Random(1234); + var inputData = new byte[1024 * 1024 * 30]; + random.NextBytes(inputData); + var inputMemoryStream = new MemoryStream(inputData); + inputMemoryStream.CopyTo(outputStream); + } + + compressedData = outputMemoryStream.ToArray(); + } + + [Benchmark] + public void DecompressData() + { + var memoryStream = new MemoryStream(compressedData); + using (var inputStream = new SharpZipLib.BZip2.BZip2InputStream(memoryStream)) + { + inputStream.CopyTo(Stream.Null); + } + } + } +} diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj b/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj index 4991a9ad1..81a8ad598 100644 --- a/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.1;net461 + netcoreapp2.1;netcoreapp3.1;net461 diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs index dca463c24..9c79e6551 100644 --- a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs @@ -13,7 +13,7 @@ public MultipleRuntimes() { AddJob(Job.Default.WithToolchain(CsProjClassicNetToolchain.Net461).AsBaseline()); // NET 4.6.1 AddJob(Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp21)); // .NET Core 2.1 - //Add(Job.Default.With(CsProjCoreToolchain.NetCoreApp30)); // .NET Core 3.0 + AddJob(Job.Default.WithToolchain(CsProjCoreToolchain.NetCoreApp31)); // .NET Core 3.1 } } diff --git a/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs b/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs index e639bc1f5..8a3d4b826 100644 --- a/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs +++ b/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs @@ -19,7 +19,11 @@ public class BZip2InputStream : Stream private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; - #endregion Constants +#if NETSTANDARD2_1 + private static readonly int VectorSize = System.Numerics.Vector.Count; +#endif + +#endregion Constants #region Instance Fields @@ -711,10 +715,27 @@ cache misses. unzftab[seqToUnseq[tmp]]++; ll8[last] = seqToUnseq[tmp]; - for (int j = nextSym - 1; j > 0; --j) + var j = nextSym - 1; + +#if !NETSTANDARD2_0 && !NETFRAMEWORK + // This is vectorized memory move. Going from the back, we're taking chunks of array + // and write them at the new location shifted by one. Since chunks are VectorSize long, + // at the end we have to move "tail" (or head actually) of the array using a plain loop. + // If System.Numerics.Vector API is not available, the plain loop is used to do the whole copying. + + while(j >= VectorSize) { - yy[j] = yy[j - 1]; + var arrayPart = new System.Numerics.Vector(yy, j - VectorSize); + arrayPart.CopyTo(yy, j - VectorSize + 1); + j -= VectorSize; } +#endif + + while(j > 0) + { + yy[j] = yy[--j]; + } + yy[0] = tmp; if (groupPos == 0) From fa08c7d0f39c735a94ce813528ffc160671bf21a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 8 May 2021 17:56:05 +0200 Subject: [PATCH 101/162] PR #621: unify PR/push CI build actions * ci: unify PR/push CI build actions * ci: build packages using .net 5 for healthy nupkgs * ci: simplify action syntax, use correct build flags --- .../{pull-request.yml => build-test.yml} | 33 +++--- .github/workflows/on-push.yml | 102 ------------------ 2 files changed, 21 insertions(+), 114 deletions(-) rename .github/workflows/{pull-request.yml => build-test.yml} (65%) delete mode 100644 .github/workflows/on-push.yml diff --git a/.github/workflows/pull-request.yml b/.github/workflows/build-test.yml similarity index 65% rename from .github/workflows/pull-request.yml rename to .github/workflows/build-test.yml index 85e91e8b2..5fb47261c 100644 --- a/.github/workflows/pull-request.yml +++ b/.github/workflows/build-test.yml @@ -1,8 +1,11 @@ -name: Build and Test PR +name: Build and Test on: pull_request: branches: [ master ] + push: + branches: [ master ] + release: jobs: Build: @@ -15,6 +18,8 @@ jobs: include: - os: windows target: net45 + env: + LIB_PROJ: src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj steps: - uses: actions/checkout@v2 @@ -24,10 +29,10 @@ jobs: dotnet-version: '3.1.x' - name: Build library (Debug) - run: dotnet build -c debug -f ${{ matrix.target }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + run: dotnet build -c debug -f ${{ matrix.target }} ${{ env.LIB_PROJ }} - name: Build library (Release) - run: dotnet build -c release -f ${{ matrix.target }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + run: dotnet build -c release -f ${{ matrix.target }} ${{ env.LIB_PROJ }} Test: runs-on: ${{ matrix.os }}-latest @@ -64,14 +69,14 @@ jobs: - name: Upload coverage to Codecov uses: codecov/codecov-action@v1.2.2 - with: - fail_ci_if_error: false Pack: needs: [Build, Test] runs-on: windows-latest env: - NUGET_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} + PKG_SUFFIX: '' + PKG_PROJ: src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + PKG_PROPS: '/p:ContinuousIntegrationBuild=true /p:EmbedUntrackedSources=true' steps: - uses: actions/checkout@v2 @@ -81,18 +86,22 @@ jobs: - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: '3.1.x' + dotnet-version: '5.0.x' - name: Build library for .NET Standard 2.0 - run: dotnet build -c Release -f netstandard2.0 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + run: dotnet build -c Release -f netstandard2.0 ${{ env.PKG_PROPS }} ${{ env.PKG_PROJ }} - name: Build library for .NET Standard 2.1 - run: dotnet build -c Release -f netstandard2.1 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + run: dotnet build -c Release -f netstandard2.1 ${{ env.PKG_PROPS }} ${{ env.PKG_PROJ }} - name: Build library for .NET Framework 4.5 - run: dotnet build -c Release -f net45 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj + run: dotnet build -c Release -f net45 ${{ env.PKG_PROPS }} ${{ env.PKG_PROJ }} + + - name: Add PR suffix to package + if: ${{ github.event_name == 'pull_request' }} + run: echo "PKG_SUFFIX=-PR" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - name: Create nuget package - run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:Version=$(git describe --abbrev | % { $_.substring(1) })-PR - + run: dotnet pack ${{ env.PKG_PROJ }} -c Release --output dist ${{ env.PKG_PROPS }} /p:Version=$(git describe --abbrev | % { $_.substring(1) })${{ env.PKG_SUFFIX }} + - name: Upload nuget package artifact uses: actions/upload-artifact@v2 with: diff --git a/.github/workflows/on-push.yml b/.github/workflows/on-push.yml deleted file mode 100644 index 3f34273d5..000000000 --- a/.github/workflows/on-push.yml +++ /dev/null @@ -1,102 +0,0 @@ -name: Build master on push - -env: - PUBLISH_DEV_PACKS: disabled - -on: - push: - branches: [ master ] - release: - -jobs: - BuildAndTest: - runs-on: ${{ matrix.os }}-latest - strategy: - fail-fast: false - matrix: - configuration: [debug, release] - os: [ubuntu, windows, macos] - libtarget: [netstandard2.0, netstandard2.1] - testtarget: [netcoreapp3.1] - include: - - configuration: debug - os: windows - libtarget: net45 - testtarget: net46 - - configuration: release - os: windows - libtarget: net45 - testtarget: net46 - steps: - - uses: actions/checkout@v2 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '3.1.x' - - - name: Build library - run: dotnet build -c ${{ matrix.configuration }} -f ${{ matrix.libtarget }} src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - - - name: Restore test dependencies - run: dotnet restore - - - name: Run tests (Debug) - if: ${{ matrix.configuration == 'debug' }} - run: dotnet test -c debug -f ${{ matrix.testtarget }} --no-restore - - - name: Run tests (Release) - if: ${{ matrix.configuration == 'release' }} - run: dotnet test -c release -f ${{ matrix.testtarget }} --no-restore --collect="XPlat Code Coverage" - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v1.2.2 - with: - fail_ci_if_error: false - - Codacy-Analysis: - runs-on: ubuntu-latest - name: Codacy Analysis CLI - steps: - - name: Checkout code - uses: actions/checkout@v2 - - name: Run codacy-analysis-cli - uses: codacy/codacy-analysis-cli-action@1.1.0 - with: - # The current issues needs to be fixed before this can be removed - max-allowed-issues: 9999 - project-token: ${{ secrets.CODACY_PROJECT_TOKEN }} - upload: true - - Package: - needs: [BuildAndTest] - runs-on: windows-latest - env: - NUGET_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} - - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - - name: Setup .NET Core - uses: actions/setup-dotnet@v1 - with: - dotnet-version: '3.1.x' - source-url: https://nuget.pkg.github.com/icsharpcode/index.json - - - name: Build library for .NET Standard 2.0 - run: dotnet build -c Release -f netstandard2.0 /p:ContinuousIntegrationBuild=true src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - - name: Build library for .NET Standard 2.1 - run: dotnet build -c Release -f netstandard2.1 /p:ContinuousIntegrationBuild=true src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - - name: Build library for .NET Framework 4.5 - run: dotnet build -c Release -f net45 /p:ContinuousIntegrationBuild=true src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - - - name: Create nuget package - run: dotnet pack src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj --configuration Release --output dist /p:ContinuousIntegrationBuild=true /p:EmbedUntrackedSources=true /p:Version=$(git describe --abbrev | % { $_.substring(1) }) - - - name: Upload nuget package artifact - uses: actions/upload-artifact@v2 - with: - name: Nuget package - path: dist/*.nupkg From 99170e149bdc084137e4397bbae745d59ad69362 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 8 May 2021 17:17:40 +0100 Subject: [PATCH 102/162] PR #587: Remove supported method checks from ZipEntry.CompressionMethod setter --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 6 +----- .../Zip/GeneralHandling.cs | 12 ------------ 2 files changed, 1 insertion(+), 17 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index c607cf9f2..f14b005f2 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -724,17 +724,13 @@ public long Crc /// /// Gets/Sets the compression method. /// - /// Throws exception when set if the method is not valid as per - /// /// /// The compression method for this entry /// public CompressionMethod CompressionMethod { get => method; - set => method = !IsCompressionMethodSupported(value) - ? throw new NotSupportedException("Compression method not supported") - : value; + set => method = value; } /// diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs index e2c2072c6..c3e32064c 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs @@ -133,18 +133,6 @@ private string DescribeAttributes(FieldAttributes attributes) return att; } - [Test] - [Category("Zip")] - //[ExpectedException(typeof(NotSupportedException))] - public void UnsupportedCompressionMethod() - { - var ze = new ZipEntry("HumblePie"); - //ze.CompressionMethod = CompressionMethod.BZip2; - - Assert.That(() => ze.CompressionMethod = CompressionMethod.Deflate64, - Throws.TypeOf()); - } - /// /// Invalid passwords should be detected early if possible, seekable stream /// Note: Have a 1/255 chance of failing due to CRC collision (hence retried once) From 7ac1fda74e1950562015f8769a0eeb65f27314cf Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 8 May 2021 17:19:17 +0100 Subject: [PATCH 103/162] #579: Implement very simple ReadAsync in ZipAESStream * add an extra unit test for doing an async read on a ZipFile InputStream * Implement ReadAsync in ZipAESStream, extra simple version --- .../Encryption/ZipAESStream.cs | 9 +++ .../Zip/ZipEncryptionHandling.cs | 65 ++++++++++++++++--- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs index 4bf01300b..80ce0b4ab 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs @@ -1,6 +1,8 @@ using System; using System.IO; using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Zip; @@ -91,6 +93,13 @@ public override int Read(byte[] buffer, int offset, int count) return nBytes; } + /// + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + var readCount = Read(buffer, offset, count); + return Task.FromResult(readCount); + } + // Read data from the underlying stream and decrypt it private int ReadAndTransform(byte[] buffer, int offset, int count) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index 34dde202b..f3a240d30 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -4,6 +4,7 @@ using System.IO; using System.Text; using ICSharpCode.SharpZipLib.Tests.TestSupport; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -149,14 +150,9 @@ public void ZipFileStoreAes() { string password = "password"; - using (var memoryStream = new MemoryStream()) + // Make an encrypted zip file + using (var memoryStream = MakeAESEncryptedZipStream(password)) { - // Try to create a zip stream - WriteEncryptedZipToStream(memoryStream, password, 256, CompressionMethod.Stored); - - // reset - memoryStream.Seek(0, SeekOrigin.Begin); - // try to read it var zipFile = new ZipFile(memoryStream, leaveOpen: true) { @@ -180,6 +176,57 @@ public void ZipFileStoreAes() } } + /// + /// As , but with Async reads + /// + [Test] + [Category("Encryption")] + [Category("Zip")] + public async Task ZipFileStoreAesAsync() + { + string password = "password"; + + // Make an encrypted zip file + using (var memoryStream = MakeAESEncryptedZipStream(password)) + { + // try to read it + var zipFile = new ZipFile(memoryStream, leaveOpen: true) + { + Password = password + }; + + foreach (ZipEntry entry in zipFile) + { + // Should be stored rather than deflated + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.Stored), "Entry should be stored"); + + using (var zis = zipFile.GetInputStream(entry)) + { + using (var inputStream = zipFile.GetInputStream(entry)) + using (var sr = new StreamReader(zis, Encoding.UTF8)) + { + var content = await sr.ReadToEndAsync(); + Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data"); + } + } + } + } + } + + // Shared helper for the ZipFileStoreAes tests + private static Stream MakeAESEncryptedZipStream(string password) + { + var memoryStream = new MemoryStream(); + + // Try to create a zip stream + WriteEncryptedZipToStream(memoryStream, password, 256, CompressionMethod.Stored); + + // reset + memoryStream.Seek(0, SeekOrigin.Begin); + + return memoryStream; + } + /// /// Test using AES encryption on a file whose contents are Stored rather than deflated /// @@ -469,7 +516,7 @@ public void ZipinputStreamShouldGracefullyFailWithAESStreams() } } - public void WriteEncryptedZipToStream(Stream stream, string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated) + public static void WriteEncryptedZipToStream(Stream stream, string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated) { using (var zs = new ZipOutputStream(stream)) { @@ -496,7 +543,7 @@ public void WriteEncryptedZipToStream(Stream stream, int entryCount, string pass } } - private void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod) + private static void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod) { ZipEntry zipEntry = new ZipEntry(entryName) { From dad484ea8e441d31b91a5fb7ed8f3f4507a75f1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 8 May 2021 18:32:29 +0200 Subject: [PATCH 104/162] fix CI badge in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1a385d929..a27570f45 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# SharpZipLib [![Build Status](https://github.com/icsharpcode/SharpZipLib/actions/workflows/on-push.yml/badge.svg?branch=master)](https://github.com/icsharpcode/SharpZipLib/actions/workflows/on-push.yml) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) +# SharpZipLib [![Build Status](https://github.com/icsharpcode/SharpZipLib/actions/workflows/build-test.yml/badge.svg?branch=master)](https://github.com/icsharpcode/SharpZipLib/actions/workflows/build-test.yml) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) Introduction ------------ From ffe69c0ad392738d70634646dcb19687548220fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 8 May 2021 18:59:54 +0200 Subject: [PATCH 105/162] PR #622: security fixes for v1.3.2 * test: alter LimitExtractPath to check for file/dir collision * fix: disallow traversal when file and base dir share name * fix: use random file name for writing asciitrans tar entries * fix: add dir separator to base dir if missing --- src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 2 +- .../Zip/WindowsNameTransform.cs | 10 +++++++++- .../Zip/FastZipHandling.cs | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs index 7bc770d17..3ae5f7757 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs @@ -824,7 +824,7 @@ private void WriteEntryCore(TarEntry sourceEntry, bool recurse) { if (!IsBinary(entryFilename)) { - tempFileName = Path.GetTempFileName(); + tempFileName = Path.GetRandomFileName(); using (StreamReader inStream = File.OpenText(entryFilename)) { diff --git a/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs b/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs index 0572cec08..43aa61403 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/WindowsNameTransform.cs @@ -1,6 +1,7 @@ using ICSharpCode.SharpZipLib.Core; using System; using System.IO; +using System.Runtime.InteropServices; using System.Text; namespace ICSharpCode.SharpZipLib.Zip @@ -133,7 +134,14 @@ public string TransformFile(string name) { name = Path.Combine(_baseDirectory, name); - if (!_allowParentTraversal && !Path.GetFullPath(name).StartsWith(_baseDirectory, StringComparison.InvariantCultureIgnoreCase)) + // Ensure base directory ends with directory separator ('/' or '\' depending on OS) + var pathBase = Path.GetFullPath(_baseDirectory); + if (pathBase[pathBase.Length - 1] != Path.DirectorySeparatorChar) + { + pathBase += Path.DirectorySeparatorChar; + } + + if (!_allowParentTraversal && !Path.GetFullPath(name).StartsWith(pathBase, StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidNameException("Parent traversal in paths is not allowed"); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 9a6baac79..396f014bb 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -474,7 +474,7 @@ public void LimitExtractPath() tempPath = Path.Combine(tempPath, uniqueName); var extractPath = Path.Combine(tempPath, "output"); - const string contentFile = "content.txt"; + const string contentFile = "output.txt"; var contentFilePathBad = Path.Combine("..", contentFile); var extractFilePathBad = Path.Combine(tempPath, contentFile); From 34879bef2b28c2b0fa991da64da83057a0b806b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 8 May 2021 19:00:47 +0200 Subject: [PATCH 106/162] update csproj for v1.3.2 release --- .../ICSharpCode.SharpZipLib.csproj | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index 6248b6287..49fcd8190 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -11,9 +11,9 @@ - 1.3.1.9 - 1.3.1.9 - 1.3.1 + 1.3.2.10 + 1.3.2.10 + 1.3.2 SharpZipLib ICSharpCode ICSharpCode @@ -22,11 +22,11 @@ http://icsharpcode.github.io/SharpZipLib/ images/sharpziplib-nuget-256x256.png https://github.com/icsharpcode/SharpZipLib - Copyright © 2000-2020 SharpZipLib Contributors + Copyright © 2000-2021 SharpZipLib Contributors Compression Library Zip GZip BZip2 LZW Tar en-US -Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.1 for more information. +Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.2 for more information. https://github.com/icsharpcode/SharpZipLib From c65486cb9f5467ac68051fbeee8e2d1df909d060 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Tue, 11 May 2021 12:24:06 +0100 Subject: [PATCH 107/162] PR #627: fix the expected/actual value ordering in unit tests --- .../Zip/FastZipHandling.cs | 2 +- .../Zip/ZipNameTransformHandling.cs | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 396f014bb..fce26c2c4 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -268,7 +268,7 @@ private void TestFileNames(IEnumerable names) { var index = z.FindEntry(name, true); - Assert.AreNotEqual(index, -1, "Zip entry \"{0}\" not found", name); + Assert.AreNotEqual(-1, index, "Zip entry \"{0}\" not found", name); var entry = z[index]; diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs index e51b8f19d..5ec8a07e8 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipNameTransformHandling.cs @@ -102,15 +102,15 @@ public void NameTransforms_Posix() [Category("Zip")] public void FilenameCleaning() { - Assert.AreEqual(ZipEntry.CleanName("hello"), "hello"); + Assert.AreEqual("hello", ZipEntry.CleanName("hello")); if(Environment.OSVersion.Platform == PlatformID.Win32NT) { - Assert.AreEqual(ZipEntry.CleanName(@"z:\eccles"), "eccles"); - Assert.AreEqual(ZipEntry.CleanName(@"\\server\share\eccles"), "eccles"); - Assert.AreEqual(ZipEntry.CleanName(@"\\server\share\dir\eccles"), "dir/eccles"); + Assert.AreEqual("eccles", ZipEntry.CleanName(@"z:\eccles")); + Assert.AreEqual("eccles", ZipEntry.CleanName(@"\\server\share\eccles")); + Assert.AreEqual("dir/eccles", ZipEntry.CleanName(@"\\server\share\dir\eccles")); } else { - Assert.AreEqual(ZipEntry.CleanName(@"/eccles"), "eccles"); + Assert.AreEqual("eccles", ZipEntry.CleanName(@"/eccles")); } } From 51343ec03d4dc6a39ee06c0b2b0037a95128e389 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Tue, 11 May 2021 12:28:02 +0100 Subject: [PATCH 108/162] PR #626: make a couple of private functions static --- src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs index 31985f93b..0b1a647fe 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs @@ -243,7 +243,7 @@ public override void Finish() #region Support Routines - private string CleanFilename(string path) + private static string CleanFilename(string path) => path.Substring(path.LastIndexOf('/') + 1); private void WriteHeader() diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index a99f1f5ba..3bd66ffeb 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -2485,7 +2485,7 @@ private void CopyBytes(ZipUpdate update, Stream destination, Stream source, /// The update to get the size for. /// Whether to include the signature size /// The descriptor size, zero if there isn't one. - private int GetDescriptorSize(ZipUpdate update, bool includingSignature) + private static int GetDescriptorSize(ZipUpdate update, bool includingSignature) { if (!((GeneralBitFlags)update.Entry.Flags).HasFlag(GeneralBitFlags.Descriptor)) return 0; From e8395008dca22771318d960ed00d2d92a0764444 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Tue, 11 May 2021 12:52:27 +0100 Subject: [PATCH 109/162] PR #625: Make BZip2Constants static instead of sealed --- src/ICSharpCode.SharpZipLib/BZip2/BZip2Constants.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/BZip2/BZip2Constants.cs b/src/ICSharpCode.SharpZipLib/BZip2/BZip2Constants.cs index 146e0a093..52fb8ad20 100644 --- a/src/ICSharpCode.SharpZipLib/BZip2/BZip2Constants.cs +++ b/src/ICSharpCode.SharpZipLib/BZip2/BZip2Constants.cs @@ -3,7 +3,7 @@ namespace ICSharpCode.SharpZipLib.BZip2 /// /// Defines internal values for both compression and decompression /// - internal sealed class BZip2Constants + internal static class BZip2Constants { /// /// Random numbers used to randomise repetitive blocks @@ -113,9 +113,5 @@ internal sealed class BZip2Constants /// Backend constant /// public const int OvershootBytes = 20; - - private BZip2Constants() - { - } } } From 232d690e4a01a1483f07c78572ecae58849900c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 11 May 2021 13:53:41 +0200 Subject: [PATCH 110/162] PR #628: Limit code coverage to windows CI --- .github/workflows/build-test.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 5fb47261c..b9217ee34 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -65,8 +65,15 @@ jobs: run: dotnet test -c debug -f ${{ matrix.target }} --no-restore - name: Run tests (Release) + # Only upload code coverage for windows in an attempt to fix the broken code coverage + if: ${{ matrix.os == 'windows' }} run: dotnet test -c release -f ${{ matrix.target }} --no-restore --collect="XPlat Code Coverage" + - name: Run tests with coverage (Release) + # Only upload code coverage for windows in an attempt to fix the broken code coverage + if: ${{ matrix.os != 'windows' }} + run: dotnet test -c release -f ${{ matrix.target }} --no-restore + - name: Upload coverage to Codecov uses: codecov/codecov-action@v1.2.2 From 08c40e89085a89424fd1af548422afa342527e5d Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Thu, 13 May 2021 17:50:43 +0100 Subject: [PATCH 111/162] PR #604: Move the Password property from DeflaterOutputStream into ZipOutputStream * Move the Password property from DeflaterOutputStream into ZipOutputStream * Move cryptoTransform setup machinery from DeflatorOutputStream to ZipOutputStream * remove duplicate setup of _aesRnd --- .../Streams/DeflaterOutputStream.cs | 65 ++----------------- .../Zip/ZipOutputStream.cs | 64 ++++++++++++++++++ 2 files changed, 68 insertions(+), 61 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs index 03cac7358..b6d4025d1 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs @@ -153,37 +153,15 @@ public bool CanPatchEntries #region Encryption - private string password; - - private ICryptoTransform cryptoTransform_; - /// - /// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream. + /// The CryptoTransform currently being used to encrypt the compressed data. /// - protected byte[] AESAuthCode; + protected ICryptoTransform cryptoTransform_; /// - /// Get/set the password used for encryption. + /// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream. /// - /// When set to null or if the password is empty no encryption is performed - public string Password - { - get - { - return password; - } - set - { - if ((value != null) && (value.Length == 0)) - { - password = null; - } - else - { - password = value; - } - } - } + protected byte[] AESAuthCode; /// /// Encrypt a block of data @@ -202,34 +180,6 @@ protected void EncryptBlock(byte[] buffer, int offset, int length) cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0); } - /// - /// Initializes encryption keys based on given . - /// - /// The password. - protected void InitializePassword(string password) - { - var pkManaged = new PkzipClassicManaged(); - byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password)); - cryptoTransform_ = pkManaged.CreateEncryptor(key, null); - } - - /// - /// Initializes encryption keys based on given password. - /// - protected void InitializeAESPassword(ZipEntry entry, string rawPassword, - out byte[] salt, out byte[] pwdVerifier) - { - salt = new byte[entry.AESSaltLen]; - // Salt needs to be cryptographically random, and unique per file - if (_aesRnd == null) - _aesRnd = RandomNumberGenerator.Create(); - _aesRnd.GetBytes(salt); - int blockSize = entry.AESKeySize / 8; // bits to bytes - - cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); - pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; - } - #endregion Encryption #region Deflation Support @@ -484,12 +434,5 @@ public override void Write(byte[] buffer, int offset, int count) private bool isClosed_; #endregion Instance Fields - - #region Static Fields - - // Static to help ensure that multiple files within a zip will get different random salt - private static RandomNumberGenerator _aesRnd = RandomNumberGenerator.Create(); - - #endregion Static Fields } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index e2c0426fd..79d65f560 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -1,5 +1,6 @@ using ICSharpCode.SharpZipLib.Checksum; using ICSharpCode.SharpZipLib.Core; +using ICSharpCode.SharpZipLib.Encryption; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using System; @@ -154,6 +155,29 @@ public UseZip64 UseZip64 /// public INameTransform NameTransform { get; set; } = new PathTransformer(); + /// + /// Get/set the password used for encryption. + /// + /// When set to null or if the password is empty no encryption is performed + public string Password + { + get + { + return password; + } + set + { + if ((value != null) && (value.Length == 0)) + { + password = null; + } + else + { + password = value; + } + } + } + /// /// Write an unsigned short in little endian byte order. /// @@ -634,6 +658,34 @@ public void CloseEntry() curEntry = null; } + /// + /// Initializes encryption keys based on given . + /// + /// The password. + private void InitializePassword(string password) + { + var pkManaged = new PkzipClassicManaged(); + byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password)); + cryptoTransform_ = pkManaged.CreateEncryptor(key, null); + } + + /// + /// Initializes encryption keys based on given password. + /// + private void InitializeAESPassword(ZipEntry entry, string rawPassword, + out byte[] salt, out byte[] pwdVerifier) + { + salt = new byte[entry.AESSaltLen]; + + // Salt needs to be cryptographically random, and unique per file + _aesRnd.GetBytes(salt); + + int blockSize = entry.AESKeySize / 8; // bits to bytes + + cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); + pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; + } + private void WriteEncryptionHeader(long crcValue) { offset += ZipConstants.CryptoHeaderSize; @@ -1010,6 +1062,18 @@ public override void Flush() // NOTE: Setting the size for entries before they are added is the best solution! private UseZip64 useZip64_ = UseZip64.Dynamic; + /// + /// The password to use when encrypting archive entries. + /// + private string password; + #endregion Instance Fields + + #region Static Fields + + // Static to help ensure that multiple files within a zip will get different random salt + private static RandomNumberGenerator _aesRnd = RandomNumberGenerator.Create(); + + #endregion Static Fields } } From 8e4d14428f382d19cb2adcad524eb885f5ff864d Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Thu, 13 May 2021 17:52:20 +0100 Subject: [PATCH 112/162] PR #634: add an async version of the WriteZipOutputStream benchmark --- .gitignore | 1 + .../Zip/ZipOutputStream.cs | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/.gitignore b/.gitignore index 7bc034335..e5f2a21e1 100644 --- a/.gitignore +++ b/.gitignore @@ -253,3 +253,4 @@ paket-files/ /test/ICSharpCode.SharpZipLib.TestBootstrapper/Properties/launchSettings.json _testRunner/ docs/help/api/.manifest +/benchmark/ICSharpCode.SharpZipLib.Benchmark/BenchmarkDotNet.Artifacts/results diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs index 0727ea6f2..ed125c1c7 100644 --- a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Zip/ZipOutputStream.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Threading.Tasks; using BenchmarkDotNet.Attributes; namespace ICSharpCode.SharpZipLib.Benchmark.Zip @@ -37,5 +38,25 @@ public long WriteZipOutputStream() return memoryStream.Position; } } + + [Benchmark] + public async Task WriteZipOutputStreamAsync() + { + using (var memoryStream = new MemoryStream(outputBuffer)) + { + using (var zipOutputStream = new SharpZipLib.Zip.ZipOutputStream(memoryStream)) + { + zipOutputStream.IsStreamOwner = false; + zipOutputStream.PutNextEntry(new SharpZipLib.Zip.ZipEntry("0")); + + for (int i = 0; i < ChunkCount; i++) + { + await zipOutputStream.WriteAsync(inputBuffer, 0, inputBuffer.Length); + } + } + + return memoryStream.Position; + } + } } } From 8c0a16904a0fa545c198c2ebe56335974925d120 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Fri, 14 May 2021 12:45:43 +0200 Subject: [PATCH 113/162] PR #636: Fix unstable tests and switch to dotcover * test: use static random seed in tests this prevents the code coverage from varying depending on how well the random data compresses * ci: use dotcover for code coverage --- .github/workflows/build-test.yml | 70 ++++++++++++++----- .../BZip2/Bzip2Tests.cs | 5 +- .../Base/InflaterDeflaterTests.cs | 7 +- .../ICSharpCode.SharpZipLib.Tests.csproj | 5 -- 4 files changed, 60 insertions(+), 27 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index b9217ee34..254ff46ed 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -22,7 +22,9 @@ jobs: LIB_PROJ: src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj steps: - uses: actions/checkout@v2 - + with: + fetch-depth: 0 + - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: @@ -39,25 +41,20 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu, windows, macos] + # Windows testing is combined with code coverage + os: [ubuntu, macos] target: [netcoreapp3.1] - include: - - os: windows - target: net46 steps: - uses: actions/checkout@v2 - + with: + fetch-depth: 0 + - name: Setup .NET Core if: matrix.target == 'netcoreapp3.1' uses: actions/setup-dotnet@v1 with: dotnet-version: '3.1.x' - # NOTE: This is the temporary fix for https://github.com/actions/virtual-environments/issues/1090 - - name: Cleanup before restore - if: ${{ matrix.os == 'windows' }} - run: dotnet clean ICSharpCode.SharpZipLib.sln && dotnet nuget locals all --clear - - name: Restore test dependencies run: dotnet restore @@ -65,20 +62,55 @@ jobs: run: dotnet test -c debug -f ${{ matrix.target }} --no-restore - name: Run tests (Release) - # Only upload code coverage for windows in an attempt to fix the broken code coverage - if: ${{ matrix.os == 'windows' }} - run: dotnet test -c release -f ${{ matrix.target }} --no-restore --collect="XPlat Code Coverage" - - - name: Run tests with coverage (Release) - # Only upload code coverage for windows in an attempt to fix the broken code coverage - if: ${{ matrix.os != 'windows' }} run: dotnet test -c release -f ${{ matrix.target }} --no-restore + + CodeCov: + name: Code Coverage + runs-on: windows-latest + env: + DOTCOVER_VER: 2021.1.2 + DOTCOVER_PKG: jetbrains.dotcover.commandlinetools + COVER_SNAPSHOT: SharpZipLib.dcvr + steps: + - uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '3.1.x' + + # NOTE: This is the temporary fix for https://github.com/actions/virtual-environments/issues/1090 + - name: Cleanup before restore + run: dotnet clean ICSharpCode.SharpZipLib.sln && dotnet nuget locals all --clear + + - name: Install codecov + run: nuget install -o tools -version ${{env.DOTCOVER_VER}} ${{env.DOTCOVER_PKG}} + + - name: Add dotcover to path + run: echo "$(pwd)\tools\${{env.DOTCOVER_PKG}}.${{env.DOTCOVER_VER}}\tools" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append + + - name: Run tests with code coverage + run: dotcover dotnet --output=${{env.COVER_SNAPSHOT}} --filters=-:ICSharpCode.SharpZipLib.Tests -- test -c release + + - name: Create code coverage report + run: dotcover report --source=${{env.COVER_SNAPSHOT}} --reporttype=detailedxml --output=dotcover-report.xml + - name: Upload coverage to Codecov uses: codecov/codecov-action@v1.2.2 + with: + files: dotcover-report.xml + + - name: Upload coverage snapshot artifact + uses: actions/upload-artifact@v2 + with: + name: Code coverage snapshot + path: ${{env.COVER_SNAPSHOT}} Pack: - needs: [Build, Test] + needs: [Build, Test, CodeCov] runs-on: windows-latest env: PKG_SUFFIX: '' diff --git a/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs b/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs index 34dc288b1..8d6febc1b 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs @@ -12,6 +12,9 @@ namespace ICSharpCode.SharpZipLib.Tests.BZip2 [TestFixture] public class BZip2Suite { + // Use the same random seed to guarantee all the code paths are followed + const int RandomSeed = 4; + /// /// Basic compress/decompress test BZip2 /// @@ -23,7 +26,7 @@ public void BasicRoundTrip() var outStream = new BZip2OutputStream(ms); byte[] buf = new byte[10000]; - var rnd = new Random(); + var rnd = new Random(RandomSeed); rnd.NextBytes(buf); outStream.Write(buf, 0, buf.Length); diff --git a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs index 6aff0a693..e6e3c4125 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs @@ -16,6 +16,9 @@ namespace ICSharpCode.SharpZipLib.Tests.Base [TestFixture] public class InflaterDeflaterTestSuite { + // Use the same random seed to guarantee all the code paths are followed + const int RandomSeed = 5; + private void Inflate(MemoryStream ms, byte[] original, int level, bool zlib) { byte[] buf2 = new byte[original.Length]; @@ -60,7 +63,7 @@ private MemoryStream Deflate(byte[] data, int level, bool zlib) private static byte[] GetRandomTestData(int size) { byte[] buffer = new byte[size]; - var rnd = new Random(); + var rnd = new Random(RandomSeed); rnd.NextBytes(buffer); return buffer; @@ -184,7 +187,7 @@ public async Task InflateDeflateZlibAsync([Range(0, 9)] int level) private int runLevel; private bool runZlib; private long runCount; - private readonly Random runRandom = new Random(5); + private readonly Random runRandom = new Random(RandomSeed); private void DeflateAndInflate(byte[] buffer) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj index 2c2a261d5..fd6f61ae9 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj +++ b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj @@ -8,15 +8,10 @@ - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - From ac96e60763966ec01394fd3c0804dbf317aaa287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Wed, 30 Jun 2021 12:16:29 +0200 Subject: [PATCH 114/162] fix(tar): create translated files in temp (#645) --- src/ICSharpCode.SharpZipLib/Core/PathUtils.cs | 2 +- src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs b/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs index 77c4b07fc..b8d0dd409 100644 --- a/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs +++ b/src/ICSharpCode.SharpZipLib/Core/PathUtils.cs @@ -36,7 +36,7 @@ public static string DropPathRoot(string path) /// /// If specified, used as the base file name for the temporary file /// Returns a temporary file name - public static string GetTempFileName(string original) + public static string GetTempFileName(string original = null) { string fileName; var tempPath = Path.GetTempPath(); diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs index 3ae5f7757..4b373fb64 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs @@ -824,7 +824,7 @@ private void WriteEntryCore(TarEntry sourceEntry, bool recurse) { if (!IsBinary(entryFilename)) { - tempFileName = Path.GetRandomFileName(); + tempFileName = PathUtils.GetTempFileName(); using (StreamReader inStream = File.OpenText(entryFilename)) { From 0cc20b430925102bb373a12f98a1c0f54ab4136a Mon Sep 17 00:00:00 2001 From: Friedrich von Never Date: Thu, 8 Jul 2021 18:03:17 +0700 Subject: [PATCH 115/162] docs(zip): fix ZipStrings typo (#648) --- src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs index 8c2447134..2d0c4cff4 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs @@ -71,7 +71,7 @@ public static int CodePage /// set the to /// /// - /// /// Get OEM codepage from NetFX, which parses the NLP file with culture info table etc etc. + /// Get OEM codepage from NetFX, which parses the NLP file with culture info table etc etc. /// But sometimes it yields the special value of 1 which is nicknamed CodePageNoOEM in sources (might also mean CP_OEMCP, but Encoding puts it so). /// This was observed on Ukranian and Hindu systems. /// Given this value, throws an . From f04d973a065fe3057f319b39d8ad03f16b2981bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 12 Aug 2021 11:25:37 +0200 Subject: [PATCH 116/162] ci: add codeql analysis --- .github/workflows/codeql-analysis.yml | 71 +++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 .github/workflows/codeql-analysis.yml diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..549469d55 --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,71 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ master ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ master ] + schedule: + - cron: '40 7 * * 4' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'csharp' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] + # Learn more: + # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed + + steps: + - name: Checkout repository + uses: actions/checkout@v2 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 From cd5310f5b7eed595110b76a2f7ae5ee013cc50f1 Mon Sep 17 00:00:00 2001 From: Jackson Wood <67569199+modio-jackson@users.noreply.github.com> Date: Thu, 12 Aug 2021 19:44:37 +1000 Subject: [PATCH 117/162] fix(bzip2): use explicit feature defs for vectorized memory move (#635) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fixed mismatched framework directives for vectorized memory move Co-authored-by: nils måsén --- .../BZip2/BZip2InputStream.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs b/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs index 8a3d4b826..3948b4e4c 100644 --- a/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs +++ b/src/ICSharpCode.SharpZipLib/BZip2/BZip2InputStream.cs @@ -1,3 +1,7 @@ +#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER + #define VECTORIZE_MEMORY_MOVE +#endif + using ICSharpCode.SharpZipLib.Checksum; using System; using System.IO; @@ -19,9 +23,9 @@ public class BZip2InputStream : Stream private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; -#if NETSTANDARD2_1 +#if VECTORIZE_MEMORY_MOVE private static readonly int VectorSize = System.Numerics.Vector.Count; -#endif +#endif // VECTORIZE_MEMORY_MOVE #endregion Constants @@ -717,7 +721,7 @@ cache misses. var j = nextSym - 1; -#if !NETSTANDARD2_0 && !NETFRAMEWORK +#if VECTORIZE_MEMORY_MOVE // This is vectorized memory move. Going from the back, we're taking chunks of array // and write them at the new location shifted by one. Since chunks are VectorSize long, // at the end we have to move "tail" (or head actually) of the array using a plain loop. @@ -729,7 +733,7 @@ cache misses. arrayPart.CopyTo(yy, j - VectorSize + 1); j -= VectorSize; } -#endif +#endif // VECTORIZE_MEMORY_MOVE while(j > 0) { From 2b8ff8fae318834b0826e649311531c65c163509 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Wed, 8 Sep 2021 12:57:11 +0200 Subject: [PATCH 118/162] update security policy the security incorrectly indicated that minor versions would receive backports of security fixes. as long as the API is fully backwards-compatible (as indicated by semver), there should be no need to release additional patches for older versions. --- SECURITY.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 1829e8c5b..1d4f9f0e4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -5,10 +5,7 @@ | Version | Supported | | ------- | ------------------ | | 1.3.x | :white_check_mark: | -| 1.2.x | :white_check_mark: | -| 1.1.x | :white_check_mark: | -| 1.0.x | :white_check_mark: | -| < 1.0 | :x: | +| < 1.3 | :x: | ## Reporting a Vulnerability From a0e96de70b5264f4c919b09253b1522bc7a221cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 18 Sep 2021 11:46:25 +0200 Subject: [PATCH 119/162] test: add tests for tar path traversal --- .../ICSharpCode.SharpZipLib.Tests.csproj | 1 + .../Tar/TarArchiveTests.cs | 73 +++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs diff --git a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj index fd6f61ae9..12183fcdd 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj +++ b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj @@ -5,6 +5,7 @@ netcoreapp3.1;net46 + 8 diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs new file mode 100644 index 000000000..e7a2bcd7f --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs @@ -0,0 +1,73 @@ +using System.IO; +using System.Text; +using ICSharpCode.SharpZipLib.Core; +using ICSharpCode.SharpZipLib.Tar; +using static ICSharpCode.SharpZipLib.Tests.TestSupport.Utils; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.Tar +{ + [TestFixture] + public class TarArchiveTests + { + [Test] + [Category("Tar")] + [Category("CreatesTempFile")] + public void ExtractingContentsWithNonTraversalPathSucceeds() + { + Assert.DoesNotThrow(() => ExtractTarOK("output", "test-good", allowTraverse: false)); + } + + [Test] + [Category("Tar")] + [Category("CreatesTempFile")] + public void ExtractingContentsWithExplicitlyAllowedTraversalPathSucceeds() + { + Assert.DoesNotThrow(() => ExtractTarOK("output", "../file", allowTraverse: true)); + } + + [Test] + [Category("Tar")] + [Category("CreatesTempFile")] + [TestCase("output", "../file")] + [TestCase("output", "../output.txt")] + public void ExtractingContentsWithDisallowedPathsFails(string outputDir, string fileName) + { + Assert.Throws(() => ExtractTarOK(outputDir, fileName, allowTraverse: false)); + } + + public void ExtractTarOK(string outputDir, string fileName, bool allowTraverse) + { + var fileContent = Encoding.UTF8.GetBytes("file content"); + using var tempDir = new TempDir(); + + var tempPath = tempDir.Fullpath; + var extractPath = Path.Combine(tempPath, outputDir); + var expectedOutputFile = Path.Combine(extractPath, fileName); + + using var archiveStream = new MemoryStream(); + + Directory.CreateDirectory(extractPath); + + using (var tos = new TarOutputStream(archiveStream, Encoding.UTF8){IsStreamOwner = false}) + { + var entry = TarEntry.CreateTarEntry(fileName); + entry.Size = fileContent.Length; + tos.PutNextEntry(entry); + tos.Write(fileContent, 0, fileContent.Length); + tos.CloseEntry(); + } + + archiveStream.Position = 0; + + using (var ta = TarArchive.CreateInputTarArchive(archiveStream, Encoding.UTF8)) + { + ta.ProgressMessageEvent += (archive, entry, message) + => TestContext.WriteLine($"{entry.Name} {entry.Size} {message}"); + ta.ExtractContents(extractPath, allowTraverse); + } + + Assert.That(File.Exists(expectedOutputFile)); + } + } +} From 5c3b293de5d65b108e7f2cd0ea8f81c1b8273f78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 18 Sep 2021 11:58:11 +0200 Subject: [PATCH 120/162] fix: specialized tar extract traversal --- src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs index 4b373fb64..aa482cc06 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs @@ -658,8 +658,9 @@ private void ExtractEntry(string destDir, TarEntry entry, bool allowParentTraver name = name.Replace('/', Path.DirectorySeparatorChar); string destFile = Path.Combine(destDir, name); + var destFileDir = Path.GetDirectoryName(Path.GetFullPath(destFile)) ?? ""; - if (!allowParentTraversal && !Path.GetFullPath(destFile).StartsWith(destDir, StringComparison.InvariantCultureIgnoreCase)) + if (!allowParentTraversal && !destFileDir.StartsWith(destDir, StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidNameException("Parent traversal in paths is not allowed"); } From 641f292ae8820b9eb56876f0eed5b4c05473f237 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 18 Sep 2021 12:01:47 +0200 Subject: [PATCH 121/162] update csproj for v1.3.3 release --- .../ICSharpCode.SharpZipLib.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index 49fcd8190..ca37ba1ae 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -11,9 +11,9 @@ - 1.3.2.10 - 1.3.2.10 - 1.3.2 + 1.3.3 + $(Version).11 + $(FileVersion) SharpZipLib ICSharpCode ICSharpCode @@ -26,7 +26,7 @@ Compression Library Zip GZip BZip2 LZW Tar en-US -Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.2 for more information. +Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.3 for more information. https://github.com/icsharpcode/SharpZipLib From a1423c470236b69c5427ab80710a00133cc25588 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 19 Sep 2021 10:08:57 +0200 Subject: [PATCH 122/162] ci: add manual dispatch and logging --- .github/workflows/build-test.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 254ff46ed..73095c685 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -1,6 +1,7 @@ name: Build and Test on: + workflow_dispatch: pull_request: branches: [ master ] push: @@ -138,6 +139,16 @@ jobs: if: ${{ github.event_name == 'pull_request' }} run: echo "PKG_SUFFIX=-PR" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + # NOTE: Should be used in next step as well, but only used for debugging for now + - name: Set package version + run: >- + $PKG_GIT_VERSION="$(git describe --abbrev | % { $_.substring(1) })" + Write-Output "Git describe: $PKG_GIT_VERSION" + Write-Output "Package suffix: $env:PKG_SUFFIX" + $PKG_VERSION = "${PKG_GIT_VERSION}${env:PKG_SUFFIX}" + Write-Output "Package version: $PKG_VERSION" + Write-Output "PKG_VERSION=$PKG_VERSION" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + - name: Create nuget package run: dotnet pack ${{ env.PKG_PROJ }} -c Release --output dist ${{ env.PKG_PROPS }} /p:Version=$(git describe --abbrev | % { $_.substring(1) })${{ env.PKG_SUFFIX }} From d21c998e8acef7e92fcc9862d668970239a8d2e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 19 Sep 2021 10:20:38 +0200 Subject: [PATCH 123/162] ci: fix yaml typo --- .github/workflows/build-test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 73095c685..c1eaad9dc 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -141,7 +141,8 @@ jobs: # NOTE: Should be used in next step as well, but only used for debugging for now - name: Set package version - run: >- + continue-on-error: true + run: |- $PKG_GIT_VERSION="$(git describe --abbrev | % { $_.substring(1) })" Write-Output "Git describe: $PKG_GIT_VERSION" Write-Output "Package suffix: $env:PKG_SUFFIX" From 1b1ab013ce1df02d8f27cf582197759c614d9126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 19 Sep 2021 11:01:54 +0200 Subject: [PATCH 124/162] ci: include non-anno tags in version --- .github/workflows/build-test.yml | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index c1eaad9dc..b6b0eeb2a 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -2,6 +2,10 @@ name: Build and Test on: workflow_dispatch: + inputs: + tag: + description: 'Tag Ref' + required: true pull_request: branches: [ master ] push: @@ -24,6 +28,7 @@ jobs: steps: - uses: actions/checkout@v2 with: + ref: ${{ github.events.inputs.tag }} fetch-depth: 0 - name: Setup .NET Core @@ -121,6 +126,7 @@ jobs: steps: - uses: actions/checkout@v2 with: + ref: ${{ github.events.inputs.tag }} fetch-depth: 0 - name: Setup .NET Core @@ -139,19 +145,18 @@ jobs: if: ${{ github.event_name == 'pull_request' }} run: echo "PKG_SUFFIX=-PR" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - # NOTE: Should be used in next step as well, but only used for debugging for now - name: Set package version continue-on-error: true run: |- - $PKG_GIT_VERSION="$(git describe --abbrev | % { $_.substring(1) })" - Write-Output "Git describe: $PKG_GIT_VERSION" - Write-Output "Package suffix: $env:PKG_SUFFIX" + $PKG_GIT_VERSION="$(git describe --tags --abbrev | % { $_.substring(1) })" + Write-Output "::notice::Git describe: $PKG_GIT_VERSION" + Write-Output "::notice::Package suffix: $env:PKG_SUFFIX" $PKG_VERSION = "${PKG_GIT_VERSION}${env:PKG_SUFFIX}" - Write-Output "Package version: $PKG_VERSION" + Write-Output "::notice::Package version: $PKG_VERSION" Write-Output "PKG_VERSION=$PKG_VERSION" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append - name: Create nuget package - run: dotnet pack ${{ env.PKG_PROJ }} -c Release --output dist ${{ env.PKG_PROPS }} /p:Version=$(git describe --abbrev | % { $_.substring(1) })${{ env.PKG_SUFFIX }} + run: dotnet pack ${{ env.PKG_PROJ }} -c Release --output dist ${{ env.PKG_PROPS }} /p:Version=${{ env.PKG_VERSION }} - name: Upload nuget package artifact uses: actions/upload-artifact@v2 From c086bc2bf79c7959afee474169f01a5b9aa4f732 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 19 Sep 2021 17:56:22 +0200 Subject: [PATCH 125/162] chore: add release notes tooling (#665) --- tools/release-notes/README.md | 10 ++++ tools/release-notes/release-notes-md.ejs | 31 ++++++++++ tools/release-notes/release-notes.js | 76 ++++++++++++++++++++++++ tools/release-notes/release-notes.json | 5 ++ 4 files changed, 122 insertions(+) create mode 100644 tools/release-notes/README.md create mode 100644 tools/release-notes/release-notes-md.ejs create mode 100644 tools/release-notes/release-notes.js create mode 100644 tools/release-notes/release-notes.json diff --git a/tools/release-notes/README.md b/tools/release-notes/README.md new file mode 100644 index 000000000..90eb018a9 --- /dev/null +++ b/tools/release-notes/README.md @@ -0,0 +1,10 @@ +## Requirements +``` +npm install -g git-release-notes +``` + +## Usage +``` +git release-notes -f release-notes.json PREVIOUS..CURRENT release-notes-md.ejs +``` +Where PREVIOUS is the previous release tag, and CURRENT is the current release tag diff --git a/tools/release-notes/release-notes-md.ejs b/tools/release-notes/release-notes-md.ejs new file mode 100644 index 000000000..afde8c298 --- /dev/null +++ b/tools/release-notes/release-notes-md.ejs @@ -0,0 +1,31 @@ +<% +const typeGroups = { + feats: { title: 'Features:', types: ['feat'] }, + fixes: { title: 'Fixes:', types: ['fix'] }, + etc: { + title: 'Other changes (not related to library code):', + types: ['docs','style','refactor','perf','test','build','ci','chore'] + }, + unknown: { title: 'Unknown:', types: ['?'] }, +} + +const commitTypes = { + feat: '✨', fix: '🐛', docs: '📚', style: '💎', + refactor: '🔨', perf: '🚀', test: '🚨', build: '📦', + ci: '⚙️', chore: '🔧', ['?']: '❓', +} + +for(const group of Object.values(typeGroups)){ + const groupCommits = commits.filter(c => group.types.includes(c.type)); + if (groupCommits.length < 1) continue; +%> +## <%=group.title%> +<% for (const {issue, title, authorName, authorUser, scope, type} of groupCommits) { %> +* <%=commitTypes[type]%> +<%=issue ? ` [[#${issue}](https://github.com/icsharpcode/SharpZipLib/pull/${issue})]\n` : ''-%> +<%=scope ? ` \`${scope}\`\n` : ''-%> + __<%=title-%>__ + by <%=authorUser ? `[_${authorName}_](https://github.com/${authorUser})` : `_${authorName}_`%> +<% } %> + +<% } %> diff --git a/tools/release-notes/release-notes.js b/tools/release-notes/release-notes.js new file mode 100644 index 000000000..ce18ccac5 --- /dev/null +++ b/tools/release-notes/release-notes.js @@ -0,0 +1,76 @@ +const https = require('https') + +const authorUsers = {} + +/** + * @param {string} email + * @param {string} prId + * @returns {Promise} User login if found */ +const getAuthorUser = async (email, prId) => { + const lookupUser = authorUsers[email]; + if (lookupUser) return lookupUser; + + const match = /[0-9]+\+([^@]+)@users\.noreply\.github\.com/.exec(email); + if (match) { + return match[1]; + } + + const pr = await new Promise((resolve, reject) => { + console.warn(`Looking up GitHub user for PR #${prId} (${email})...`) + https.get(`https://api.github.com/repos/icsharpcode/sharpziplib/pulls/${prId}`, { + headers: {Accept: 'application/vnd.github.v3+json', 'User-Agent': 'release-notes-script/0.3.1'} + }, (res) => { + res.setEncoding('utf8'); + let chunks = ''; + res.on('data', (chunk) => chunks += chunk); + res.on('end', () => resolve(JSON.parse(chunks))); + res.on('error', reject); + }).on('error', reject); + }).catch(e => { + console.error(`Could not get GitHub user (${email}): ${e}}`) + return null; + }); + + if (!pr) { + console.error(`Could not get GitHub user (${email})}`) + return null; + } else { + const user = pr.user.login; + console.warn(`Resolved email ${email} to user ${user}`) + authorUsers[email] = user; + return user; + } +} + +/** + * @typedef {{issue?: string, sha1: string, authorEmail: string, title: string, type: string}} Commit + * @param {{commits: Commit[], range: string, dateFnsFormat: ()=>any, debug: (...p[]) => void}} data + * @param {(data: {commits: Commit[], extra: {[key: string]: any}}) => void} callback + * */ +module.exports = (data, callback) => { + // Migrates commits in the old format to conventional commit style, omitting any commits in neither format + const normalizedCommits = data.commits.flatMap(c => { + if (c.type) return [c] + const match = /^(?:Merge )?(?:PR ?)?#(\d+):? (.*)/.exec(c.title) + if (match != null) { + const [, issue, title] = match + return [{...c, title, issue, type: '?'}] + } else { + console.warn(`Skipping commit [${c.sha1.substr(0, 7)}] "${c.title}"!`); + return []; + } + }); + + const commitAuthoredBy = email => commit => commit.authorEmail === email && commit.issue ? [commit.issue] : [] + const authorEmails = new Set(normalizedCommits.map(c => c.authorEmail)); + Promise.all( + Array + .from(authorEmails.values(), e => [e, normalizedCommits.flatMap(commitAuthoredBy(e))]) + .map(async ([email, prs]) => [email, await getAuthorUser(email, ...prs)]) + ) + .then(Object.fromEntries) + .then(authorUsers => callback({ + commits: normalizedCommits.map(c => ({...c, authorUser: authorUsers[c.authorEmail]})), + extra: {} + })) +}; diff --git a/tools/release-notes/release-notes.json b/tools/release-notes/release-notes.json new file mode 100644 index 000000000..7ad7733d1 --- /dev/null +++ b/tools/release-notes/release-notes.json @@ -0,0 +1,5 @@ +{ + "title" : "^([a-z]+)(?:\\(([\\w\\$\\.]*)\\))?\\: (.*?)(?: \\(#(\\d+)\\))?$", + "meaning": ["type", "scope", "title", "issue"], + "script": "release-notes.js" +} From 61d36ee0b6ec9cf98e8465e72f448b62cc42fee6 Mon Sep 17 00:00:00 2001 From: ueli-werner Date: Mon, 20 Sep 2021 13:08:42 +0200 Subject: [PATCH 126/162] docs(zip): fix slash names in CleanName comment (#668) --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index f14b005f2..ffeee1883 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -1089,7 +1089,7 @@ public static bool IsCompressionMethodSupported(CompressionMethod method) /// /// Cleans a name making it conform to Zip file conventions. /// Devices names ('c:\') and UNC share names ('\\server\share') are removed - /// and forward slashes ('\') are converted to back slashes ('/'). + /// and back slashes ('\') are converted to forward slashes ('/'). /// Names are made relative by trimming leading slashes which is compatible /// with the ZIP naming convention. /// From b5b1a92b477de8841c5ed5f3dcd6e8eb80ff53bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 21 Sep 2021 09:52:37 +0200 Subject: [PATCH 127/162] fix(tar): permit slashed output dir (#666) --- src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 2 +- .../Tar/TarArchiveTests.cs | 21 +++++++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs index aa482cc06..6db6b23b9 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs @@ -613,7 +613,7 @@ public void ExtractContents(string destinationDirectory, bool allowParentTravers throw new ObjectDisposedException("TarArchive"); } - var fullDistDir = Path.GetFullPath(destinationDirectory); + var fullDistDir = Path.GetFullPath(destinationDirectory).TrimEnd('/', '\\'); while (true) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs index e7a2bcd7f..374a9b1e3 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs @@ -13,9 +13,12 @@ public class TarArchiveTests [Test] [Category("Tar")] [Category("CreatesTempFile")] - public void ExtractingContentsWithNonTraversalPathSucceeds() + [TestCase("output")] + [TestCase("output/")] + [TestCase(@"output\", IncludePlatform = "Win")] + public void ExtractingContentsWithNonTraversalPathSucceeds(string outputDir) { - Assert.DoesNotThrow(() => ExtractTarOK("output", "test-good", allowTraverse: false)); + Assert.DoesNotThrow(() => ExtractTarOK(outputDir, "file", allowTraverse: false)); } [Test] @@ -30,12 +33,26 @@ public void ExtractingContentsWithExplicitlyAllowedTraversalPathSucceeds() [Category("Tar")] [Category("CreatesTempFile")] [TestCase("output", "../file")] + [TestCase("output/", "../file")] [TestCase("output", "../output.txt")] public void ExtractingContentsWithDisallowedPathsFails(string outputDir, string fileName) { Assert.Throws(() => ExtractTarOK(outputDir, fileName, allowTraverse: false)); } + [Test] + [Category("Tar")] + [Category("CreatesTempFile")] + [Platform(Include = "Win", Reason = "Backslashes are only treated as path separators on windows")] + [TestCase(@"output\", @"..\file")] + [TestCase(@"output/", @"..\file")] + [TestCase("output", @"..\output.txt")] + [TestCase(@"output\", @"..\output.txt")] + public void ExtractingContentsOnWindowsWithDisallowedPathsFails(string outputDir, string fileName) + { + Assert.Throws(() => ExtractTarOK(outputDir, fileName, allowTraverse: false)); + } + public void ExtractTarOK(string outputDir, string fileName, bool allowTraverse) { var fileContent = Encoding.UTF8.GetBytes("file content"); From d31fac3dc924d22733b42df3868064cb88735611 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 9 Oct 2021 18:15:22 +0200 Subject: [PATCH 128/162] test: repeatability and refactoring (#671) --- .../BZip2/Bzip2Tests.cs | 37 +- .../Base/InflaterDeflaterTests.cs | 61 ++-- .../GZip/GZipTests.cs | 148 +++----- .../Tar/TarArchiveTests.cs | 5 +- .../Tar/TarTests.cs | 230 ++++++------ .../TestSupport/StringTesting.cs | 41 +-- .../TestSupport/Utils.cs | 285 +++++++++------ .../Zip/FastZipHandling.cs | 223 ++++++------ .../Zip/StreamHandling.cs | 190 +++++----- .../Zip/ZipFileHandling.cs | 335 ++++++++---------- 10 files changed, 719 insertions(+), 836 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs b/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs index 8d6febc1b..62d5a7874 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/BZip2/Bzip2Tests.cs @@ -1,7 +1,6 @@ using ICSharpCode.SharpZipLib.BZip2; using ICSharpCode.SharpZipLib.Tests.TestSupport; using NUnit.Framework; -using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tests.BZip2 @@ -24,34 +23,30 @@ public void BasicRoundTrip() { var ms = new MemoryStream(); var outStream = new BZip2OutputStream(ms); + + var buf = Utils.GetDummyBytes(size: 10000, RandomSeed); - byte[] buf = new byte[10000]; - var rnd = new Random(RandomSeed); - rnd.NextBytes(buf); - - outStream.Write(buf, 0, buf.Length); + outStream.Write(buf, offset: 0, buf.Length); outStream.Close(); ms = new MemoryStream(ms.GetBuffer()); - ms.Seek(0, SeekOrigin.Begin); + ms.Seek(offset: 0, SeekOrigin.Begin); - using (BZip2InputStream inStream = new BZip2InputStream(ms)) + using BZip2InputStream inStream = new BZip2InputStream(ms); + var buf2 = new byte[buf.Length]; + var pos = 0; + while (true) { - byte[] buf2 = new byte[buf.Length]; - int pos = 0; - while (true) + var numRead = inStream.Read(buf2, pos, count: 4096); + if (numRead <= 0) { - int numRead = inStream.Read(buf2, pos, 4096); - if (numRead <= 0) - { - break; - } - pos += numRead; + break; } + pos += numRead; + } - for (int i = 0; i < buf.Length; ++i) - { - Assert.AreEqual(buf2[i], buf[i]); - } + for (var i = 0; i < buf.Length; ++i) + { + Assert.AreEqual(buf2[i], buf[i]); } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs index e6e3c4125..9df9319b4 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs @@ -60,20 +60,10 @@ private MemoryStream Deflate(byte[] data, int level, bool zlib) return memoryStream; } - private static byte[] GetRandomTestData(int size) - { - byte[] buffer = new byte[size]; - var rnd = new Random(RandomSeed); - rnd.NextBytes(buffer); - - return buffer; - } - private void RandomDeflateInflate(int size, int level, bool zlib) { - byte[] buffer = GetRandomTestData(size); - - MemoryStream ms = Deflate(buffer, level, zlib); + var buffer = Utils.GetDummyBytes(size, RandomSeed); + var ms = Deflate(buffer, level, zlib); Inflate(ms, buffer, level, zlib); } @@ -130,9 +120,8 @@ private async Task DeflateAsync(byte[] data, int level, bool zlib) private async Task RandomDeflateInflateAsync(int size, int level, bool zlib) { - byte[] buffer = GetRandomTestData(size); - - MemoryStream ms = await DeflateAsync(buffer, level, zlib); + var buffer = Utils.GetDummyBytes(size, RandomSeed); + var ms = await DeflateAsync(buffer, level, zlib); await InflateAsync(ms, buffer, level, zlib); } @@ -179,24 +168,21 @@ public void InflateDeflateZlib([Range(0, 9)] int level) [Category("Async")] public async Task InflateDeflateZlibAsync([Range(0, 9)] int level) { - await RandomDeflateInflateAsync(100000, level, true); + await RandomDeflateInflateAsync(size: 100000, level, zlib: true); } private delegate void RunCompress(byte[] buffer); - private int runLevel; - private bool runZlib; - private long runCount; - private readonly Random runRandom = new Random(RandomSeed); + private int _runLevel; + private bool _runZlib; private void DeflateAndInflate(byte[] buffer) { - ++runCount; - MemoryStream ms = Deflate(buffer, runLevel, runZlib); - Inflate(ms, buffer, runLevel, runZlib); + var ms = Deflate(buffer, _runLevel, _runZlib); + Inflate(ms, buffer, _runLevel, _runZlib); } - private void TryVariants(RunCompress test, byte[] buffer, int index) + private void TryVariants(RunCompress test, byte[] buffer, Random random, int index) { int worker = 0; while (worker <= 255) @@ -204,33 +190,34 @@ private void TryVariants(RunCompress test, byte[] buffer, int index) buffer[index] = (byte)worker; if (index < buffer.Length - 1) { - TryVariants(test, buffer, index + 1); + TryVariants(test, buffer, random, index + 1); } else { test(buffer); } - worker += runRandom.Next(256); + worker += random.Next(maxValue: 256); } } private void TryManyVariants(int level, bool zlib, RunCompress test, byte[] buffer) { - runLevel = level; - runZlib = zlib; - TryVariants(test, buffer, 0); + var random = new Random(RandomSeed); + _runLevel = level; + _runZlib = zlib; + TryVariants(test, buffer, random, 0); } // TODO: Fix this - //[Test] - //[Category("Base")] - //public void SmallBlocks() - //{ - // byte[] buffer = new byte[10]; - // Array.Clear(buffer, 0, buffer.Length); - // TryManyVariants(0, false, new RunCompress(DeflateAndInflate), buffer); - //} + [Test] + [Category("Base")] + [Explicit("Long-running")] + public void SmallBlocks() + { + var buffer = new byte[10]; + TryManyVariants(level: 0, zlib: false, DeflateAndInflate, buffer); + } /// /// Basic inflate/deflate test diff --git a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs index 8a9f61d69..62be609fc 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs @@ -23,9 +23,7 @@ public void TestGZip() var ms = new MemoryStream(); var outStream = new GZipOutputStream(ms); - byte[] buf = new byte[100000]; - var rnd = new Random(); - rnd.NextBytes(buf); + var buf = Utils.GetDummyBytes(size: 100000); outStream.Write(buf, 0, buf.Length); outStream.Flush(); @@ -64,17 +62,15 @@ public void TestGZip() [Category("GZip")] public void DelayedHeaderWriteNoData() { - var ms = new MemoryStream(); - Assert.AreEqual(0, ms.Length); + using var ms = new MemoryStream(); + Assert.Zero(ms.Length); - using (GZipOutputStream outStream = new GZipOutputStream(ms)) + using (new GZipOutputStream(ms)) { - Assert.AreEqual(0, ms.Length); + Assert.Zero(ms.Length); } - byte[] data = ms.ToArray(); - - Assert.IsTrue(data.Length > 0); + Assert.NotZero(ms.ToArray().Length); } @@ -260,7 +256,7 @@ public void DoubleClose() s.Close(); memStream = new TrackedMemoryStream(); - using (GZipOutputStream no2 = new GZipOutputStream(memStream)) + using (new GZipOutputStream(memStream)) { s.Close(); } @@ -273,14 +269,7 @@ public void WriteAfterFinish() var s = new GZipOutputStream(memStream); s.Finish(); - try - { - s.WriteByte(7); - Assert.Fail("Write should fail"); - } - catch - { - } + Assert.Throws(() => s.WriteByte(value: 7), "Write should fail"); } [Test] @@ -290,14 +279,7 @@ public void WriteAfterClose() var s = new GZipOutputStream(memStream); s.Close(); - try - { - s.WriteByte(7); - Assert.Fail("Write should fail"); - } - catch - { - } + Assert.Throws(() => s.WriteByte(value: 7), "Write should fail"); } /// @@ -311,9 +293,7 @@ public void TrailingGarbage() var outStream = new GZipOutputStream(ms); // input buffer to be compressed - byte[] buf = new byte[100000]; - var rnd = new Random(); - rnd.NextBytes(buf); + var buf = Utils.GetDummyBytes(size: 100000, seed: 3); // compress input buffer outStream.Write(buf, 0, buf.Length); @@ -321,9 +301,7 @@ public void TrailingGarbage() outStream.Finish(); // generate random trailing garbage and add to the compressed stream - byte[] garbage = new byte[4096]; - rnd.NextBytes(garbage); - ms.Write(garbage, 0, garbage.Length); + Utils.WriteDummyData(ms, size: 4096, seed: 4); // rewind the concatenated stream ms.Seek(0, SeekOrigin.Begin); @@ -336,7 +314,7 @@ public void TrailingGarbage() int count = buf2.Length; while (true) { - int numRead = inStream.Read(buf2, currentIndex, count); + var numRead = inStream.Read(buf2, currentIndex, count); if (numRead <= 0) { break; @@ -346,7 +324,7 @@ public void TrailingGarbage() } /* ASSERT */ - Assert.AreEqual(0, count); + Assert.Zero(count); for (int i = 0; i < buf.Length; ++i) { Assert.AreEqual(buf2[i], buf[i]); @@ -365,9 +343,7 @@ public void FlushToUnderlyingStream() var ms = new MemoryStream(); var outStream = new GZipOutputStream(ms); - byte[] buf = new byte[100000]; - var rnd = new Random(); - rnd.NextBytes(buf); + byte[] buf = Utils.GetDummyBytes(size: 100000); outStream.Write(buf, 0, buf.Length); // Flush output stream but don't finish it yet @@ -414,48 +390,43 @@ public void SmallBufferDecompression() { var outputBufferSize = 100000; var inputBufferSize = outputBufferSize * 4; + var inputBuffer = Utils.GetDummyBytes(inputBufferSize, seed: 0); var outputBuffer = new byte[outputBufferSize]; - var inputBuffer = new byte[inputBufferSize]; - - using (var msGzip = new MemoryStream()) - { - using (var gzos = new GZipOutputStream(msGzip)) - { - gzos.IsStreamOwner = false; - var rnd = new Random(0); - rnd.NextBytes(inputBuffer); - gzos.Write(inputBuffer, 0, inputBuffer.Length); + using var msGzip = new MemoryStream(); + using (var gzos = new GZipOutputStream(msGzip)) + { + gzos.IsStreamOwner = false; - gzos.Flush(); - gzos.Finish(); - } + gzos.Write(inputBuffer, 0, inputBuffer.Length); + + gzos.Flush(); + gzos.Finish(); + } - msGzip.Seek(0, SeekOrigin.Begin); + msGzip.Seek(0, SeekOrigin.Begin); - using (var gzis = new GZipInputStream(msGzip)) - using (var msRaw = new MemoryStream()) - { + using (var gzis = new GZipInputStream(msGzip)) + using (var msRaw = new MemoryStream()) + { - int readOut; - while ((readOut = gzis.Read(outputBuffer, 0, outputBuffer.Length)) > 0) - { - msRaw.Write(outputBuffer, 0, readOut); - } + int readOut; + while ((readOut = gzis.Read(outputBuffer, 0, outputBuffer.Length)) > 0) + { + msRaw.Write(outputBuffer, 0, readOut); + } - var resultBuffer = msRaw.ToArray(); + var resultBuffer = msRaw.ToArray(); - for (var i = 0; i < resultBuffer.Length; i++) - { - Assert.AreEqual(inputBuffer[i], resultBuffer[i]); - } + for (var i = 0; i < resultBuffer.Length; i++) + { + Assert.AreEqual(inputBuffer[i], resultBuffer[i]); + } - } } - } /// @@ -467,18 +438,13 @@ public void SmallBufferDecompression() /// [Test] [Category("Zip")] - public void ShouldGracefullyHandleReadingANonReableStream() + public void ShouldGracefullyHandleReadingANonReadableStream() { MemoryStream ms = new SelfClosingStream(); using (var gzos = new GZipOutputStream(ms)) { gzos.IsStreamOwner = false; - - byte[] buf = new byte[100000]; - var rnd = new Random(); - rnd.NextBytes(buf); - - gzos.Write(buf, 0, buf.Length); + Utils.WriteDummyData(gzos, size: 100000); } ms.Seek(0, SeekOrigin.Begin); @@ -526,30 +492,26 @@ public void OriginalFilename() var content = "FileContents"; - using (var ms = new MemoryStream()) + using var ms = new MemoryStream(); + using (var outStream = new GZipOutputStream(ms) { IsStreamOwner = false }) { - using (var outStream = new GZipOutputStream(ms) { IsStreamOwner = false }) - { - outStream.FileName = "/path/to/file.ext"; + outStream.FileName = "/path/to/file.ext"; - var writeBuffer = Encoding.ASCII.GetBytes(content); - outStream.Write(writeBuffer, 0, writeBuffer.Length); - outStream.Flush(); - outStream.Finish(); - } + var writeBuffer = Encoding.ASCII.GetBytes(content); + outStream.Write(writeBuffer, 0, writeBuffer.Length); + outStream.Flush(); + outStream.Finish(); + } - ms.Seek(0, SeekOrigin.Begin); + ms.Seek(0, SeekOrigin.Begin); - using (var inStream = new GZipInputStream(ms)) - { - var readBuffer = new byte[content.Length]; - inStream.Read(readBuffer, 0, readBuffer.Length); - Assert.AreEqual(content, Encoding.ASCII.GetString(readBuffer)); - Assert.AreEqual("file.ext", inStream.GetFilename()); - } - + using (var inStream = new GZipInputStream(ms)) + { + var readBuffer = new byte[content.Length]; + inStream.Read(readBuffer, 0, readBuffer.Length); + Assert.AreEqual(content, Encoding.ASCII.GetString(readBuffer)); + Assert.AreEqual("file.ext", inStream.GetFilename()); } - } } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs index 374a9b1e3..d9e32194a 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarArchiveTests.cs @@ -2,6 +2,7 @@ using System.Text; using ICSharpCode.SharpZipLib.Core; using ICSharpCode.SharpZipLib.Tar; +using ICSharpCode.SharpZipLib.Tests.TestSupport; using static ICSharpCode.SharpZipLib.Tests.TestSupport.Utils; using NUnit.Framework; @@ -56,9 +57,9 @@ public void ExtractingContentsOnWindowsWithDisallowedPathsFails(string outputDir public void ExtractTarOK(string outputDir, string fileName, bool allowTraverse) { var fileContent = Encoding.UTF8.GetBytes("file content"); - using var tempDir = new TempDir(); + using var tempDir = GetTempDir(); - var tempPath = tempDir.Fullpath; + var tempPath = tempDir.FullName; var extractPath = Path.Combine(tempPath, outputDir); var expectedOutputFile = Path.Combine(extractPath, fileName); diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs index 5cdd9404e..fae87a736 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs @@ -5,6 +5,7 @@ using System; using System.IO; using System.Text; +using NUnit.Framework.Internal; namespace ICSharpCode.SharpZipLib.Tests.Tar { @@ -35,8 +36,8 @@ public void Setup() public void EmptyTar() { var ms = new MemoryStream(); - int recordSize = 0; - using (TarArchive tarOut = TarArchive.CreateOutputTarArchive(ms)) + int recordSize; + using (var tarOut = TarArchive.CreateOutputTarArchive(ms)) { recordSize = tarOut.RecordSize; } @@ -48,12 +49,12 @@ public void EmptyTar() ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); - using (TarArchive tarIn = TarArchive.CreateInputTarArchive(ms2, null)) + using (var tarIn = TarArchive.CreateInputTarArchive(ms2, nameEncoding: null)) { entryCount = 0; tarIn.ProgressMessageEvent += EntryCounter; tarIn.ListContents(); - Assert.AreEqual(0, entryCount, "Expected 0 tar entries"); + Assert.Zero(entryCount, "Expected 0 tar entries"); } } @@ -64,27 +65,24 @@ public void EmptyTar() [Category("Tar")] public void BlockFactorHandling() { - const int MinimumBlockFactor = 1; - const int MaximumBlockFactor = 64; - const int FillFactor = 2; + const int minimumBlockFactor = 1; + const int maximumBlockFactor = 64; + const int fillFactor = 2; - for (int factor = MinimumBlockFactor; factor < MaximumBlockFactor; ++factor) + for (var factor = minimumBlockFactor; factor < maximumBlockFactor; ++factor) { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms, factor, null)) + using (var tarOut = new TarOutputStream(ms, factor, nameEncoding: null)) { - TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); - entry.Size = (TarBuffer.BlockSize * factor * FillFactor); + var entry = TarEntry.CreateTarEntry("TestEntry"); + entry.Size = TarBuffer.BlockSize * factor * fillFactor; tarOut.PutNextEntry(entry); - byte[] buffer = new byte[TarBuffer.BlockSize]; - - var r = new Random(); - r.NextBytes(buffer); + var buffer = Utils.GetDummyBytes(TarBuffer.BlockSize); // Last block is a partial one - for (int i = 0; i < factor * FillFactor; ++i) + for (var i = 0; i < factor * fillFactor; ++i) { tarOut.Write(buffer, 0, buffer.Length); } @@ -94,7 +92,7 @@ public void BlockFactorHandling() Assert.IsNotNull(tarData, "Data written is null"); // Blocks = Header + Data Blocks + Zero block + Record trailer - int usedBlocks = 1 + (factor * FillFactor) + 2; + int usedBlocks = 1 + (factor * fillFactor) + 2; int totalBlocks = usedBlocks + (factor - 1); totalBlocks /= factor; totalBlocks *= factor; @@ -102,20 +100,18 @@ public void BlockFactorHandling() Assert.AreEqual(TarBuffer.BlockSize * totalBlocks, tarData.Length, "Tar file should contain {0} blocks in length", totalBlocks); - if (usedBlocks < totalBlocks) + if (usedBlocks >= totalBlocks) continue; + + // Start at first byte after header. + var byteIndex = TarBuffer.BlockSize * ((factor * fillFactor) + 1); + while (byteIndex < tarData.Length) { - // Start at first byte after header. - int byteIndex = TarBuffer.BlockSize * ((factor * FillFactor) + 1); - while (byteIndex < tarData.Length) - { - int blockNumber = byteIndex / TarBuffer.BlockSize; - int offset = blockNumber % TarBuffer.BlockSize; - Assert.AreEqual(0, tarData[byteIndex], - string.Format("Trailing block data should be null iteration {0} block {1} offset {2} index {3}", - factor, - blockNumber, offset, byteIndex)); - byteIndex += 1; - } + var blockNumber = byteIndex / TarBuffer.BlockSize; + var offset = blockNumber % TarBuffer.BlockSize; + Assert.AreEqual(0, tarData[byteIndex], + "Trailing block data should be null iteration {0} block {1} offset {2} index {3}", + factor, blockNumber, offset, byteIndex); + byteIndex += 1; } } } @@ -127,13 +123,13 @@ public void BlockFactorHandling() [Category("Tar")] public void TrailerContainsNulls() { - const int TestBlockFactor = 3; + const int testBlockFactor = 3; - for (int iteration = 0; iteration < TestBlockFactor * 2; ++iteration) + for (int iteration = 0; iteration < testBlockFactor * 2; ++iteration) { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms, TestBlockFactor, null)) + using (TarOutputStream tarOut = new TarOutputStream(ms, testBlockFactor, null)) { TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); if (iteration > 0) @@ -167,9 +163,9 @@ public void TrailerContainsNulls() // Blocks = Header + Data Blocks + Zero block + Record trailer int usedBlocks = 1 + iteration + 2; - int totalBlocks = usedBlocks + (TestBlockFactor - 1); - totalBlocks /= TestBlockFactor; - totalBlocks *= TestBlockFactor; + int totalBlocks = usedBlocks + (testBlockFactor - 1); + totalBlocks /= testBlockFactor; + totalBlocks *= testBlockFactor; Assert.AreEqual(TarBuffer.BlockSize * totalBlocks, tarData.Length, string.Format("Tar file should be {0} blocks in length", totalBlocks)); @@ -195,7 +191,7 @@ public void TrailerContainsNulls() private void TryLongName(string name) { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms, null)) + using (TarOutputStream tarOut = new TarOutputStream(ms, nameEncoding: null)) { DateTime modTime = DateTime.Now; @@ -207,7 +203,7 @@ private void TryLongName(string name) ms2.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); ms2.Seek(0, SeekOrigin.Begin); - using (TarInputStream tarIn = new TarInputStream(ms2, null)) + using (TarInputStream tarIn = new TarInputStream(ms2, nameEncoding: null)) { TarEntry nextEntry = tarIn.GetNextEntry(); @@ -290,20 +286,15 @@ public void ExtendedHeaderLongName() var buffer = new byte[2560]; var truncated = Convert.FromBase64String(input64); Array.Copy(truncated, buffer, truncated.Length); - truncated = null; - - using (var ms = new MemoryStream(buffer)) - using (var tis = new TarInputStream(ms, null)) - { - var entry = tis.GetNextEntry(); - Assert.IsNotNull(entry, "Entry is null"); - Assert.IsNotNull(entry.Name, "Entry name is null"); - - Assert.AreEqual(expectedName.Length, entry.Name.Length, $"Entry name is truncated to {entry.Name.Length} bytes."); - - Assert.AreEqual(expectedName, entry.Name, "Entry name does not match expected value"); - } + using var ms = new MemoryStream(buffer); + using var tis = new TarInputStream(ms, nameEncoding: null); + var entry = tis.GetNextEntry(); + + Assert.IsNotNull(entry, "Entry is null"); + Assert.IsNotNull(entry.Name, "Entry name is null"); + Assert.AreEqual(expectedName.Length, entry.Name.Length, $"Entry name is truncated to {entry.Name.Length} bytes."); + Assert.AreEqual(expectedName, entry.Name, "Entry name does not match expected value"); } /// @@ -394,11 +385,9 @@ public void HeaderEquality() public void Checksum() { var ms = new MemoryStream(); - using (TarOutputStream tarOut = new TarOutputStream(ms, null)) + using (var tarOut = new TarOutputStream(ms, nameEncoding: null)) { - DateTime modTime = DateTime.Now; - - TarEntry entry = TarEntry.CreateTarEntry("TestEntry"); + var entry = TarEntry.CreateTarEntry("TestEntry"); entry.TarHeader.Mode = 12345; tarOut.PutNextEntry(entry); @@ -409,7 +398,7 @@ public void Checksum() ms2.Seek(0, SeekOrigin.Begin); TarEntry nextEntry; - using (TarInputStream tarIn = new TarInputStream(ms2, null)) + using (var tarIn = new TarInputStream(ms2, nameEncoding: null)) { nextEntry = tarIn.GetNextEntry(); Assert.IsTrue(nextEntry.TarHeader.IsChecksumValid, "Checksum should be valid"); @@ -421,20 +410,9 @@ public void Checksum() ms3.Write(new byte[] { 34 }, 0, 1); ms3.Seek(0, SeekOrigin.Begin); - using (TarInputStream tarIn = new TarInputStream(ms3, null)) + using (var tarIn = new TarInputStream(ms3, nameEncoding: null)) { - bool trapped = false; - - try - { - nextEntry = tarIn.GetNextEntry(); - } - catch (TarException) - { - trapped = true; - } - - Assert.IsTrue(trapped, "Checksum should be invalid"); + Assert.Throws(() => tarIn.GetNextEntry(), "Checksum should be invalid"); } } @@ -703,37 +681,35 @@ public void EndBlockHandling() long outCount, inCount; - using (var ms = new MemoryStream()) + using var ms = new MemoryStream(); + using (var tarOut = TarArchive.CreateOutputTarArchive(ms)) + using (var dummyFile = Utils.GetDummyFile(dummySize)) { - using (var tarOut = TarArchive.CreateOutputTarArchive(ms)) - using (var dummyFile = Utils.GetDummyFile(dummySize)) - { - tarOut.IsStreamOwner = false; - tarOut.WriteEntry(TarEntry.CreateEntryFromFile(dummyFile.Filename), false); - } + tarOut.IsStreamOwner = false; + tarOut.WriteEntry(TarEntry.CreateEntryFromFile(dummyFile), recurse: false); + } - outCount = ms.Position; - ms.Seek(0, SeekOrigin.Begin); + outCount = ms.Position; + ms.Seek(0, SeekOrigin.Begin); - using (var tarIn = TarArchive.CreateInputTarArchive(ms, null)) - using (var tempDir = new Utils.TempDir()) - { - tarIn.IsStreamOwner = false; - tarIn.ExtractContents(tempDir.Fullpath); + using (var tarIn = TarArchive.CreateInputTarArchive(ms, nameEncoding: null)) + using (var tempDir = Utils.GetTempDir()) + { + tarIn.IsStreamOwner = false; + tarIn.ExtractContents(tempDir); - foreach (var file in Directory.GetFiles(tempDir.Fullpath, "*", SearchOption.AllDirectories)) - { - Console.WriteLine($"Extracted \"{file}\""); - } + foreach (var file in Directory.GetFiles(tempDir, "*", SearchOption.AllDirectories)) + { + Console.WriteLine($"Extracted \"{file}\""); } + } - inCount = ms.Position; + inCount = ms.Position; - Console.WriteLine($"Output count: {outCount}"); - Console.WriteLine($"Input count: {inCount}"); + Console.WriteLine($"Output count: {outCount}"); + Console.WriteLine($"Input count: {inCount}"); - Assert.AreEqual(inCount, outCount, "Bytes read and bytes written should be equal"); - } + Assert.AreEqual(inCount, outCount, "Bytes read and bytes written should be equal"); } [Test] @@ -742,14 +718,14 @@ public void EndBlockHandling() [Explicit("Long Running")] public void WriteThroughput() { - const string EntryName = "LargeTarEntry"; + const string entryName = "LargeTarEntry"; PerformanceTesting.TestWrite(TestDataSize.Large, bs => { - var tos = new TarOutputStream(bs, null); + var tos = new TarOutputStream(bs, nameEncoding: null); tos.PutNextEntry(new TarEntry(new TarHeader() { - Name = EntryName, + Name = entryName, Size = (int)TestDataSize.Large, })); return tos; @@ -766,7 +742,7 @@ public void WriteThroughput() [Explicit("Long Running")] public void SingleLargeEntry() { - const string EntryName = "LargeTarEntry"; + const string entryName = "LargeTarEntry"; const TestDataSize dataSize = TestDataSize.Large; PerformanceTesting.TestReadWrite( @@ -776,7 +752,7 @@ public void SingleLargeEntry() var tis = new TarInputStream(bs, null); var entry = tis.GetNextEntry(); - Assert.AreEqual(EntryName, entry.Name); + Assert.AreEqual(entryName, entry.Name); return tis; }, output: bs => @@ -784,7 +760,7 @@ public void SingleLargeEntry() var tos = new TarOutputStream(bs, null); tos.PutNextEntry(new TarEntry(new TarHeader() { - Name = EntryName, + Name = entryName, Size = (int)dataSize, })); return tos; @@ -801,44 +777,40 @@ public void SingleLargeEntry() [Category("Tar")] public void ExtractingCorruptTarShouldntLeakFiles() { - using (var memoryStream = new MemoryStream()) + using var memoryStream = new MemoryStream(); + //Create a tar.gz in the output stream + using (var gzipStream = new GZipOutputStream(memoryStream)) { - //Create a tar.gz in the output stream - using (var gzipStream = new GZipOutputStream(memoryStream)) - { - gzipStream.IsStreamOwner = false; + gzipStream.IsStreamOwner = false; - using (var tarOut = TarArchive.CreateOutputTarArchive(gzipStream)) - using (var dummyFile = Utils.GetDummyFile(32000)) - { - tarOut.IsStreamOwner = false; - tarOut.WriteEntry(TarEntry.CreateEntryFromFile(dummyFile.Filename), false); - } + using (var tarOut = TarArchive.CreateOutputTarArchive(gzipStream)) + using (var dummyFile = Utils.GetDummyFile(size: 32000)) + { + tarOut.IsStreamOwner = false; + tarOut.WriteEntry(TarEntry.CreateEntryFromFile(dummyFile), recurse: false); } + } - // corrupt archive - make sure the file still has more than one block - memoryStream.SetLength(16000); - memoryStream.Seek(0, SeekOrigin.Begin); - - // try to extract - using (var gzipStream = new GZipInputStream(memoryStream)) - { - string tempDirName; - gzipStream.IsStreamOwner = false; + // corrupt archive - make sure the file still has more than one block + memoryStream.SetLength(16000); + memoryStream.Seek(0, SeekOrigin.Begin); - using (var tempDir = new Utils.TempDir()) - { - tempDirName = tempDir.Fullpath; - - using (var tarIn = TarArchive.CreateInputTarArchive(gzipStream, null)) - { - tarIn.IsStreamOwner = false; - Assert.Throws(() => tarIn.ExtractContents(tempDir.Fullpath)); - } - } + // try to extract + using (var gzipStream = new GZipInputStream(memoryStream)) + { + gzipStream.IsStreamOwner = false; - Assert.That(Directory.Exists(tempDirName), Is.False, "Temporary folder should have been removed"); + using var tempDir = Utils.GetTempDir(); + using (var tarIn = TarArchive.CreateInputTarArchive(gzipStream, nameEncoding: null)) + { + tarIn.IsStreamOwner = false; + Assert.Throws(() => tarIn.ExtractContents(tempDir)); } + + // Try to remove the output directory to check if any file handles are still being held + Assert.DoesNotThrow(() => tempDir.Delete()); + + Assert.That(tempDir.Exists, Is.False, "Temporary folder should have been removed"); } } [TestCase(10, "utf-8")] diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/StringTesting.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/StringTesting.cs index 3d67a9c70..e1d7a1fb0 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/StringTesting.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/StringTesting.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; namespace ICSharpCode.SharpZipLib.Tests.TestSupport { @@ -6,36 +7,20 @@ public static class StringTesting { static StringTesting() { - AddLanguage("Chinese", "測試.txt", "big5"); - AddLanguage("Greek", "Ϗΰ.txt", "windows-1253"); - AddLanguage("Nordic", "Åæ.txt", "windows-1252"); - AddLanguage("Arabic", "ڀڅ.txt", "windows-1256"); - AddLanguage("Russian", "Прйвёт.txt", "windows-1251"); - } - - private static void AddLanguage(string language, string filename, string encoding) - { - languages.Add(language); - filenames.Add(filename); - encodings.Add(encoding); - entries++; + TestSamples = new [] + { + ("Chinese", "測試.txt", "big5"), + ("Greek", "Ϗΰ.txt", "windows-1253"), + ("Nordic", "Åæ.txt", "windows-1252"), + ("Arabic", "ڀڅ.txt", "windows-1256"), + ("Russian", "Прйвёт.txt", "windows-1251"), + }; } - private static int entries = 0; - private static List languages = new List(); - private static List filenames = new List(); - private static List encodings = new List(); + public static (string language, string filename, string encoding)[] TestSamples { get; } - public static IEnumerable Languages => filenames.AsReadOnly(); - public static IEnumerable Filenames => filenames.AsReadOnly(); - public static IEnumerable Encodings => filenames.AsReadOnly(); - - public static IEnumerable<(string language, string filename, string encoding)> GetTestSamples() - { - for (int i = 0; i < entries; i++) - { - yield return (languages[i], filenames[i], encodings[i]); - } - } + public static IEnumerable Languages => TestSamples.Select(s => s.language); + public static IEnumerable Filenames => TestSamples.Select(s => s.filename); + public static IEnumerable Encodings => TestSamples.Select(s => s.encoding); } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs index 33d6e3e9b..179202b44 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs @@ -1,7 +1,7 @@ using NUnit.Framework; using System; using System.IO; -using System.Text; +using System.Linq; namespace ICSharpCode.SharpZipLib.Tests.TestSupport { @@ -10,9 +10,7 @@ namespace ICSharpCode.SharpZipLib.Tests.TestSupport /// public static class Utils { - public static int DummyContentLength = 16; - - private static Random random = new Random(); + internal const int DefaultSeed = 5; /// /// Returns the system root for the current platform (usually c:\ for windows and / for others) @@ -40,125 +38,200 @@ private static void Compare(byte[] a, byte[] b) } } - public static void WriteDummyData(string fileName, int size = -1) + /// + /// Write pseudo-random data to , + /// creating it if it does not exist or truncating it otherwise + /// + /// + /// + /// + public static void WriteDummyData(string fileName, int size, int seed = DefaultSeed) { - using(var fs = File.OpenWrite(fileName)) - { - WriteDummyData(fs, size); - } + using var fs = File.Create(fileName); + WriteDummyData(fs, size, seed); } - public static void WriteDummyData(Stream stream, int size = -1) + /// + /// Write pseudo-random data to + /// + /// + /// + /// + public static void WriteDummyData(Stream stream, int size, int seed = DefaultSeed) { - var bytes = (size < 0) - ? Encoding.ASCII.GetBytes(DateTime.UtcNow.Ticks.ToString("x16")) - : new byte[size]; - - if(size > 0) - { - random.NextBytes(bytes); - } - - stream.Write(bytes, 0, bytes.Length); + var bytes = GetDummyBytes(size, seed); + stream.Write(bytes, offset: 0, bytes.Length); + } + + /// + /// Creates a buffer of pseudo-random bytes + /// + /// + /// + /// + public static byte[] GetDummyBytes(int size, int seed = DefaultSeed) + { + var random = new Random(seed); + var bytes = new byte[size]; + random.NextBytes(bytes); + return bytes; } - public static TempFile GetDummyFile(int size = -1) + /// + /// Returns a file reference with bytes of dummy data written to it + /// + /// + /// + public static TempFile GetDummyFile(int size = 16) { var tempFile = new TempFile(); - WriteDummyData(tempFile.Filename, size); + using var fs = tempFile.Create(); + WriteDummyData(fs, size); return tempFile; } + /// + /// Returns a randomized file/directory name (without any path) using a generated GUID + /// + /// public static string GetDummyFileName() - => $"{random.Next():x8}{random.Next():x8}{random.Next():x8}"; - - public class TempFile : IDisposable - { - public string Filename { get; internal set; } - - public TempFile() - { - Filename = Path.GetTempFileName(); - } + => string.Concat(Guid.NewGuid().ToByteArray().Select(b => $"{b:x2}")); - #region IDisposable Support - - private bool disposed = false; // To detect redundant calls - - protected virtual void Dispose(bool disposing) - { - if (!disposed) - { - if (disposing && File.Exists(Filename)) - { - try - { - File.Delete(Filename); - } - catch { } - } - - disposed = true; - } - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - #endregion IDisposable Support - } - - public class TempDir : IDisposable - { - public string Fullpath { get; internal set; } - - public TempDir() - { - Fullpath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); - Directory.CreateDirectory(Fullpath); - } - - #region IDisposable Support - - private bool disposed = false; // To detect redundant calls + /// + /// Returns a reference to a temporary directory that deletes it's contents when disposed + /// + /// + public static TempDir GetTempDir() => new TempDir(); - protected virtual void Dispose(bool disposing) - { - if (!disposed) - { - if (disposing && Directory.Exists(Fullpath)) - { - try - { - Directory.Delete(Fullpath, true); - } - catch { } - } - - disposed = true; - } - } + /// + /// Returns a reference to a temporary file that deletes it's referred file when disposed + /// + /// + public static TempFile GetTempFile() => new TempFile(); + } + + public class TempFile : FileSystemInfo, IDisposable + { + private FileInfo _fileInfo; - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } + public override string Name => _fileInfo.Name; + public override bool Exists => _fileInfo.Exists; + public string DirectoryName => _fileInfo.DirectoryName; - internal string CreateDummyFile(int size = -1) - => CreateDummyFile(GetDummyFileName(), size); + public override string FullName => _fileInfo.FullName; - internal string CreateDummyFile(string name, int size = -1) - { - var fileName = Path.Combine(Fullpath, name); - WriteDummyData(fileName, size); - return fileName; - } + public byte[] ReadAllBytes() => File.ReadAllBytes(_fileInfo.FullName); - #endregion IDisposable Support - } + public static implicit operator string(TempFile tf) => tf._fileInfo.FullName; + + public override void Delete() + { + if(!Exists) return; + _fileInfo.Delete(); + } + + public FileStream Create() => _fileInfo.Create(); + + public static TempFile WithDummyData(int size, string dirPath = null, string filename = null, int seed = Utils.DefaultSeed) + { + var tempFile = new TempFile(dirPath, filename); + Utils.WriteDummyData(tempFile.FullName, size, seed); + return tempFile; + } + + internal TempFile(string dirPath = null, string filename = null) + { + dirPath ??= Path.GetTempPath(); + filename ??= Utils.GetDummyFileName(); + _fileInfo = new FileInfo(Path.Combine(dirPath, filename)); + } + + #region IDisposable Support + + private bool _disposed; // To detect redundant calls + + protected virtual void Dispose(bool disposing) + { + if (_disposed) return; + if (disposing) + { + try + { + Delete(); + } + catch + { + // ignored + } + } + + _disposed = true; + } + + public void Dispose() + { + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + + #endregion IDisposable Support + + } + public class TempDir : FileSystemInfo, IDisposable + { + public override string Name => Path.GetFileName(FullName); + public override bool Exists => Directory.Exists(FullName); + + public static implicit operator string(TempDir td) => td.FullName; + + public override void Delete() + { + if(!Exists) return; + Directory.Delete(FullPath, recursive: true); + } + + public TempDir() + { + FullPath = Path.Combine(Path.GetTempPath(), Utils.GetDummyFileName()); + Directory.CreateDirectory(FullPath); + } + + public TempFile CreateDummyFile(int size = 16, int seed = Utils.DefaultSeed) + => CreateDummyFile(null, size); + + public TempFile CreateDummyFile(string name, int size = 16, int seed = Utils.DefaultSeed) + => TempFile.WithDummyData(size, FullPath, name, seed); + + public TempFile GetFile(string fileName) => new TempFile(FullPath, fileName); + + #region IDisposable Support + + private bool _disposed; // To detect redundant calls + + protected virtual void Dispose(bool disposing) + { + if (_disposed) return; + if (disposing) + { + try + { + Delete(); + } + catch + { + // ignored + } + } + _disposed = true; + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + #endregion IDisposable Support + } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index fce26c2c4..f1c9863da 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -103,12 +103,12 @@ public void ExtractEmptyDirectories() [Category("CreatesTempFile")] public void CreateEmptyDirectories(string password) { - using (var tempFilePath = new Utils.TempDir()) + using (var tempFilePath = Utils.GetTempDir()) { - string name = Path.Combine(tempFilePath.Fullpath, "x.zip"); + string name = Path.Combine(tempFilePath.FullName, "x.zip"); // Create empty test folders (The folder that we'll zip, and the test sub folder). - string archiveRootDir = Path.Combine(tempFilePath.Fullpath, ZipTempDir); + string archiveRootDir = Path.Combine(tempFilePath.FullName, ZipTempDir); string targetDir = Path.Combine(archiveRootDir, "floyd"); Directory.CreateDirectory(targetDir); @@ -118,7 +118,7 @@ public void CreateEmptyDirectories(string password) CreateEmptyDirectories = true, Password = password, }; - fastZip.CreateZip(name, archiveRootDir, true, null); + fastZip.CreateZip(name, archiveRootDir, recurse: true, fileFilter: null); // Test that the archive contains the empty folder entry using (var zipFile = new ZipFile(name)) @@ -128,7 +128,7 @@ public void CreateEmptyDirectories(string password) var folderEntry = zipFile.GetEntry("floyd/"); Assert.That(folderEntry.IsDirectory, Is.True, "The entry must be a folder"); - Assert.IsTrue(zipFile.TestArchive(true)); + Assert.IsTrue(zipFile.TestArchive(testData: true)); } } } @@ -138,25 +138,24 @@ public void CreateEmptyDirectories(string password) [Category("CreatesTempFile")] public void ContentEqualAfterAfterArchived([Values(0, 1, 64)]int contentSize) { - using(var sourceDir = new Utils.TempDir()) - using(var targetDir = new Utils.TempDir()) - using(var zipFile = Utils.GetDummyFile(0)) - { - var sourceFile = sourceDir.CreateDummyFile(contentSize); - var sourceContent = File.ReadAllBytes(sourceFile); - new FastZip().CreateZip(zipFile.Filename, sourceDir.Fullpath, true, null); - - Assert.DoesNotThrow(() => - { - new FastZip().ExtractZip(zipFile.Filename, targetDir.Fullpath, null); - }, "Exception during extraction of test archive"); + using var sourceDir = Utils.GetTempDir(); + using var targetDir = Utils.GetTempDir(); + using var zipFile = Utils.GetTempFile(); + + var sourceFile = sourceDir.CreateDummyFile(contentSize); + var sourceContent = sourceFile.ReadAllBytes(); + new FastZip().CreateZip(zipFile.FullName, sourceDir.FullName, recurse: true, fileFilter: null); + + Assert.DoesNotThrow(() => + { + new FastZip().ExtractZip(zipFile, targetDir, fileFilter: null); + }, "Exception during extraction of test archive"); - var targetFile = Path.Combine(targetDir.Fullpath, Path.GetFileName(sourceFile)); - var targetContent = File.ReadAllBytes(targetFile); + var targetFile = Path.Combine(targetDir, Path.GetFileName(sourceFile)); + var targetContent = File.ReadAllBytes(targetFile); - Assert.AreEqual(sourceContent.Length, targetContent.Length, "Extracted file size does not match source file size"); - Assert.AreEqual(sourceContent, targetContent, "Extracted content does not match source content"); - } + Assert.AreEqual(sourceContent.Length, targetContent.Length, "Extracted file size does not match source file size"); + Assert.AreEqual(sourceContent, targetContent, "Extracted content does not match source content"); } [Test] @@ -230,64 +229,55 @@ public void CreateExceptions() { Assert.Throws(() => { - using (var tempDir = new Utils.TempDir()) - { - var fastZip = new FastZip(); - var badPath = Path.Combine(Path.GetTempPath(), Utils.GetDummyFileName()); - var addFile = Path.Combine(tempDir.Fullpath, "test.zip"); - fastZip.CreateZip(addFile, badPath, false, null); - } + using var tempDir = Utils.GetTempDir(); + var fastZip = new FastZip(); + var badPath = Path.Combine(Path.GetTempPath(), Utils.GetDummyFileName()); + var addFile = tempDir.GetFile("test.zip"); + fastZip.CreateZip(addFile, badPath, recurse: false, fileFilter: null); }); } #region String testing helper - private void TestFileNames(params string[] names) - => TestFileNames((IEnumerable)names); - - private void TestFileNames(IEnumerable names) + private void TestFileNames(IReadOnlyList names) { var zippy = new FastZip(); - using (var tempDir = new Utils.TempDir()) - using (var tempZip = new Utils.TempFile()) + using var tempDir = Utils.GetTempDir(); + using var tempZip = Utils.GetTempFile(); + int nameCount = 0; + foreach (var name in names) { - int nameCount = 0; - foreach (var name in names) - { - tempDir.CreateDummyFile(name); - nameCount++; - } + tempDir.CreateDummyFile(name); + nameCount++; + } - zippy.CreateZip(tempZip.Filename, tempDir.Fullpath, true, null); + zippy.CreateZip(tempZip, tempDir, recurse: true, fileFilter: null); - using (ZipFile z = new ZipFile(tempZip.Filename)) - { - Assert.AreEqual(nameCount, z.Count); - foreach (var name in names) - { - var index = z.FindEntry(name, true); + using var zf = new ZipFile(tempZip); + Assert.AreEqual(nameCount, zf.Count); + foreach (var name in names) + { + var index = zf.FindEntry(name, ignoreCase: true); - Assert.AreNotEqual(-1, index, "Zip entry \"{0}\" not found", name); + Assert.AreNotEqual(expected: -1, index, "Zip entry \"{0}\" not found", name); - var entry = z[index]; + var entry = zf[index]; - if (ZipStrings.UseUnicode) - { - Assert.IsTrue(entry.IsUnicodeText, "Zip entry #{0} not marked as unicode", index); - } - else - { - Assert.IsFalse(entry.IsUnicodeText, "Zip entry #{0} marked as unicode", index); - } + if (ZipStrings.UseUnicode) + { + Assert.IsTrue(entry.IsUnicodeText, "Zip entry #{0} not marked as unicode", index); + } + else + { + Assert.IsFalse(entry.IsUnicodeText, "Zip entry #{0} marked as unicode", index); + } - Assert.AreEqual(name, entry.Name); + Assert.AreEqual(name, entry.Name); - var nameBytes = string.Join(" ", Encoding.BigEndianUnicode.GetBytes(entry.Name).Select(b => b.ToString("x2"))); + var nameBytes = string.Join(" ", Encoding.BigEndianUnicode.GetBytes(entry.Name).Select(b => b.ToString("x2"))); - Console.WriteLine($" - Zip entry: {entry.Name} ({nameBytes})"); - } - } + Console.WriteLine($" - Zip entry: {entry.Name} ({nameBytes})"); } } @@ -301,7 +291,7 @@ public void UnicodeText() var preCp = ZipStrings.CodePage; try { - TestFileNames(StringTesting.Filenames); + TestFileNames(StringTesting.Filenames.ToArray()); } finally { @@ -319,7 +309,7 @@ public void NonUnicodeText() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - foreach ((string language, string filename, string encoding) in StringTesting.GetTestSamples()) + foreach (var (language, filename, encoding) in StringTesting.TestSamples) { Console.WriteLine($"{language} filename \"{filename}\" using \"{encoding}\":"); @@ -337,7 +327,7 @@ public void NonUnicodeText() } ZipStrings.CodePage = Encoding.GetEncoding(encoding).CodePage; - TestFileNames(filename); + TestFileNames(new []{filename}); } } finally @@ -659,32 +649,27 @@ public void CreateZipShouldLeaveOutputStreamOpenIfRequested(bool leaveOpen) { const string tempFileName = "a(2).dat"; - using (var tempFolder = new Utils.TempDir()) - { - // Create test input file - string addFile = Path.Combine(tempFolder.Fullpath, tempFileName); - MakeTempFile(addFile, 16); + using var tempFolder = Utils.GetTempDir(); + // Create test input file + tempFolder.CreateDummyFile(tempFileName, size: 16); - // Create the zip with fast zip - var target = new TrackedMemoryStream(); - var fastZip = new FastZip(); + // Create the zip with fast zip + var target = new TrackedMemoryStream(); + var fastZip = new FastZip(); - fastZip.CreateZip(target, tempFolder.Fullpath, false, @"a\(2\)\.dat", null, leaveOpen: leaveOpen); + fastZip.CreateZip(target, tempFolder, recurse: false, @"a\(2\)\.dat", directoryFilter: null, leaveOpen); - // Check that the output stream was disposed (or not) as expected - Assert.That(target.IsDisposed, Is.Not.EqualTo(leaveOpen), "IsDisposed should be the opposite of leaveOpen"); + // Check that the output stream was disposed (or not) as expected + Assert.That(target.IsDisposed, Is.Not.EqualTo(leaveOpen), "IsDisposed should be the opposite of leaveOpen"); - // Check that the file contents are correct in both cases - var archive = new MemoryStream(target.ToArray()); - using (ZipFile zf = new ZipFile(archive)) - { - Assert.AreEqual(1, zf.Count); - ZipEntry entry = zf[0]; - Assert.AreEqual(tempFileName, entry.Name); - Assert.AreEqual(16, entry.Size); - Assert.IsTrue(zf.TestArchive(true)); - } - } + // Check that the file contents are correct in both cases + var archive = new MemoryStream(target.ToArray()); + using var zf = new ZipFile(archive); + Assert.AreEqual(expected: 1, zf.Count); + var entry = zf[0]; + Assert.AreEqual(tempFileName, entry.Name); + Assert.AreEqual(expected: 16, entry.Size); + Assert.IsTrue(zf.TestArchive(testData: true)); } [Category("Zip")] @@ -748,15 +733,13 @@ public void ExtractZipShouldSetTimeOnFilesFromConstructorTimeSetting(TimeSetting } var fastZip = new FastZip(timeSetting); - using (var extractDir = new Utils.TempDir()) - { - fastZip.ExtractZip(archiveStream, extractDir.Fullpath, FastZip.Overwrite.Always, - _ => true, "", "", true, true, false); - var fi = new FileInfo(Path.Combine(extractDir.Fullpath, SingleEntryFileName)); - var actualTime = FileTimeFromTimeSetting(fi, timeSetting); - // Assert that the time is within +/- 2s of the target time to allow for timing/rounding discrepancies - Assert.LessOrEqual(Math.Abs((targetTime - actualTime).TotalSeconds), 2); - } + using var extractDir = Utils.GetTempDir(); + fastZip.ExtractZip(archiveStream, extractDir.FullName, FastZip.Overwrite.Always, + _ => true, "", "", restoreDateTime: true, isStreamOwner: true, allowParentTraversal: false); + var fi = new FileInfo(Path.Combine(extractDir.FullName, SingleEntryFileName)); + var actualTime = FileTimeFromTimeSetting(fi, timeSetting); + // Assert that the time is within +/- 2s of the target time to allow for timing/rounding discrepancies + Assert.LessOrEqual(Math.Abs((targetTime - actualTime).TotalSeconds), 2); } [Category("Zip")] @@ -770,15 +753,13 @@ public void ExtractZipShouldSetTimeOnFilesFromConstructorDateTime(DateTimeKind d // Extract the archive with a fixed time override var targetTime = ExpectedFixedTime(dtk); var fastZip = new FastZip(targetTime); - using (var extractDir = new Utils.TempDir()) - { - fastZip.ExtractZip(target, extractDir.Fullpath, FastZip.Overwrite.Always, - _ => true, "", "", true, true, false); - var fi = new FileInfo(Path.Combine(extractDir.Fullpath, SingleEntryFileName)); - var fileTime = FileTimeFromTimeSetting(fi, TimeSetting.Fixed); - if (fileTime.Kind != dtk) fileTime = fileTime.ToUniversalTime(); - Assert.AreEqual(targetTime, fileTime); - } + using var extractDir = Utils.GetTempDir(); + fastZip.ExtractZip(target, extractDir.FullName, FastZip.Overwrite.Always, + _ => true, "", "", restoreDateTime: true, isStreamOwner: true, allowParentTraversal: false); + var fi = new FileInfo(Path.Combine(extractDir.FullName, SingleEntryFileName)); + var fileTime = FileTimeFromTimeSetting(fi, TimeSetting.Fixed); + if (fileTime.Kind != dtk) fileTime = fileTime.ToUniversalTime(); + Assert.AreEqual(targetTime, fileTime); } [Category("Zip")] @@ -792,13 +773,11 @@ public void ExtractZipShouldSetTimeOnFilesWithEmptyConstructor(DateTimeKind dtk) // Extract the archive with an empty constructor var fastZip = new FastZip(); - using (var extractDir = new Utils.TempDir()) - { - fastZip.ExtractZip(target, extractDir.Fullpath, FastZip.Overwrite.Always, - _ => true, "", "", true, true, false); - var fi = new FileInfo(Path.Combine(extractDir.Fullpath, SingleEntryFileName)); - Assert.AreEqual(targetTime, FileTimeFromTimeSetting(fi, TimeSetting.Fixed)); - } + using var extractDir = Utils.GetTempDir(); + fastZip.ExtractZip(target, extractDir.FullName, FastZip.Overwrite.Always, + _ => true, "", "", restoreDateTime: true, isStreamOwner: true, allowParentTraversal: false); + var fi = new FileInfo(Path.Combine(extractDir.FullName, SingleEntryFileName)); + Assert.AreEqual(targetTime, FileTimeFromTimeSetting(fi, TimeSetting.Fixed)); } private static bool IsLastAccessTime(TimeSetting ts) @@ -851,17 +830,15 @@ private static TrackedMemoryStream CreateFastZipTestArchiveWithAnEntry(FastZip f { var target = new TrackedMemoryStream(); - using (var tempFolder = new Utils.TempDir()) - { + using var tempFolder = Utils.GetTempDir(); + // Create test input file + var addFile = Path.Combine(tempFolder.FullName, SingleEntryFileName); + MakeTempFile(addFile, 16); + var fi = new FileInfo(addFile); + alterFile?.Invoke(fi); - // Create test input file - var addFile = Path.Combine(tempFolder.Fullpath, SingleEntryFileName); - MakeTempFile(addFile, 16); - var fi = new FileInfo(addFile); - alterFile?.Invoke(fi); - - fastZip.CreateZip(target, tempFolder.Fullpath, false, SingleEntryFileName, null, leaveOpen: true); - } + fastZip.CreateZip(target, tempFolder.FullName, recurse: false, + SingleEntryFileName, directoryFilter: null, leaveOpen: true); return target; } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index 7a336592a..3e8b9a9ee 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -44,9 +44,9 @@ public void ParameterHandling() ms.Seek(0, SeekOrigin.Begin); var inStream = new ZipInputStream(ms); - ZipEntry e = inStream.GetNextEntry(); + inStream.GetNextEntry(); - MustFailRead(inStream, null, 0, 0); + MustFailRead(inStream, buffer: null, 0, 0); MustFailRead(inStream, buffer, -1, 1); MustFailRead(inStream, buffer, 0, 11); MustFailRead(inStream, buffer, 7, 5); @@ -114,14 +114,13 @@ public void ReadAndWriteZip64NonSeekable() msw.Position = 0; - using (ZipInputStream zis = new ZipInputStream(msw)) + using (var zis = new ZipInputStream(msw)) { while (zis.GetNextEntry() != null) { - int len = 0; - int bufferSize = 1024; - byte[] buffer = new byte[bufferSize]; - while ((len = zis.Read(buffer, 0, bufferSize)) > 0) + const int bufferSize = 1024; + var buffer = new byte[bufferSize]; + while (zis.Read(buffer, 0, bufferSize) > 0) { // Reading the data is enough } @@ -241,46 +240,40 @@ public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLengt { var buffer = new byte[255]; - using (var dummyZip = Utils.GetDummyFile(0)) - using (var inputFile = Utils.GetDummyFile(contentLength)) - { - // Filename is manually cleaned here to prevent this test from failing while ZipEntry doesn't automatically clean it - var inputFileName = ZipEntry.CleanName(inputFile.Filename); + using var dummyZip = Utils.GetTempFile(); + using var inputFile = Utils.GetDummyFile(contentLength); + // Filename is manually cleaned here to prevent this test from failing while ZipEntry doesn't automatically clean it + var inputFileName = ZipEntry.CleanName(inputFile); - using (var zipFileStream = File.OpenWrite(dummyZip.Filename)) - using (var zipOutputStream = new ZipOutputStream(zipFileStream)) - using (var inputFileStream = File.OpenRead(inputFile.Filename)) + using (var zipFileStream = File.OpenWrite(dummyZip)) + using (var zipOutputStream = new ZipOutputStream(zipFileStream)) + using (var inputFileStream = File.OpenRead(inputFile)) + { + zipOutputStream.PutNextEntry(new ZipEntry(inputFileName) { - zipOutputStream.PutNextEntry(new ZipEntry(inputFileName) - { - CompressionMethod = CompressionMethod.Stored, - }); - - StreamUtils.Copy(inputFileStream, zipOutputStream, buffer); - } + CompressionMethod = CompressionMethod.Stored, + }); - using (var zf = new ZipFile(dummyZip.Filename)) - { - var inputBytes = File.ReadAllBytes(inputFile.Filename); + StreamUtils.Copy(inputFileStream, zipOutputStream, buffer); + } - var entry = zf.GetEntry(inputFileName); - Assert.IsNotNull(entry, "No entry matching source file \"{0}\" found in archive, found \"{1}\"", inputFileName, zf[0].Name); + using (var zf = new ZipFile(dummyZip)) + { + var inputBytes = File.ReadAllBytes(inputFile); - Assert.DoesNotThrow(() => - { - using (var entryStream = zf.GetInputStream(entry)) - { - var outputBytes = new byte[entryStream.Length]; - entryStream.Read(outputBytes, 0, outputBytes.Length); + var entry = zf.GetEntry(inputFileName); + Assert.IsNotNull(entry, "No entry matching source file \"{0}\" found in archive, found \"{1}\"", inputFileName, zf[0].Name); - Assert.AreEqual(inputBytes, outputBytes, "Archive content does not match the source content"); - } - }, "Failed to locate entry stream in archive"); + Assert.DoesNotThrow(() => + { + using var entryStream = zf.GetInputStream(entry); + var outputBytes = new byte[entryStream.Length]; + entryStream.Read(outputBytes, 0, outputBytes.Length); - Assert.IsTrue(zf.TestArchive(testData: true), "Archive did not pass TestArchive"); - } + Assert.AreEqual(inputBytes, outputBytes, "Archive content does not match the source content"); + }, "Failed to locate entry stream in archive"); - + Assert.IsTrue(zf.TestArchive(testData: true), "Archive did not pass TestArchive"); } } @@ -288,26 +281,25 @@ public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLengt [Category("Zip")] public void ZipEntryFileNameAutoClean() { - using (var dummyZip = Utils.GetDummyFile(0)) - using (var inputFile = Utils.GetDummyFile()) { - using (var zipFileStream = File.OpenWrite(dummyZip.Filename)) - using (var zipOutputStream = new ZipOutputStream(zipFileStream)) - using (var inputFileStream = File.OpenRead(inputFile.Filename)) + using var dummyZip = Utils.GetDummyFile(0); + using var inputFile = Utils.GetDummyFile(); + using (var zipFileStream = File.OpenWrite(dummyZip)) + using (var zipOutputStream = new ZipOutputStream(zipFileStream)) + using (var inputFileStream = File.OpenRead(inputFile)) + { + // New ZipEntry created with a full file name path as it's name + zipOutputStream.PutNextEntry(new ZipEntry(inputFile) { - // New ZipEntry created with a full file name path as it's name - zipOutputStream.PutNextEntry(new ZipEntry(inputFile.Filename) - { - CompressionMethod = CompressionMethod.Stored, - }); + CompressionMethod = CompressionMethod.Stored, + }); - inputFileStream.CopyTo(zipOutputStream); - } + inputFileStream.CopyTo(zipOutputStream); + } - using (var zf = new ZipFile(dummyZip.Filename)) - { - // The ZipEntry name should have been automatically cleaned - Assert.AreEqual(ZipEntry.CleanName(inputFile.Filename), zf[0].Name); - } + using (var zf = new ZipFile(dummyZip)) + { + // The ZipEntry name should have been automatically cleaned + Assert.AreEqual(ZipEntry.CleanName(inputFile), zf[0].Name); } } @@ -424,7 +416,7 @@ public void WriteThroughput() [Explicit("Long Running")] public void SingleLargeEntry() { - const string EntryName = "CantSeek"; + const string entryName = "CantSeek"; PerformanceTesting.TestReadWrite( size: TestDataSize.Large, @@ -433,14 +425,14 @@ public void SingleLargeEntry() var zis = new ZipInputStream(bs); var entry = zis.GetNextEntry(); - Assert.AreEqual(EntryName, entry.Name); + Assert.AreEqual(entryName, entry.Name); Assert.IsTrue((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0); return zis; }, output: bs => { var zos = new ZipOutputStream(bs); - zos.PutNextEntry(new ZipEntry(EntryName)); + zos.PutNextEntry(new ZipEntry(entryName)); return zos; } ); @@ -458,20 +450,18 @@ public void SingleLargeEntry() [Category("Zip")] public void ShouldReadBZip2EntryButNotDecompress() { - var fileBytes = System.Convert.FromBase64String(BZip2CompressedZip); + var fileBytes = Convert.FromBase64String(BZip2CompressedZip); - using (var input = new MemoryStream(fileBytes, false)) - { - var zis = new ZipInputStream(input); - var entry = zis.GetNextEntry(); + using var input = new MemoryStream(fileBytes, writable: false); + var zis = new ZipInputStream(input); + var entry = zis.GetNextEntry(); - Assert.That(entry.Name, Is.EqualTo("a.dat"), "Should be able to get entry name"); - Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Entry should be BZip2 compressed"); - Assert.That(zis.CanDecompressEntry, Is.False, "Should not be able to decompress BZip2 entry"); + Assert.That(entry.Name, Is.EqualTo("a.dat"), "Should be able to get entry name"); + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Entry should be BZip2 compressed"); + Assert.That(zis.CanDecompressEntry, Is.False, "Should not be able to decompress BZip2 entry"); - var buffer = new byte[1]; - Assert.Throws(() => zis.Read(buffer, 0, 1), "Trying to read the stream should throw"); - } + var buffer = new byte[1]; + Assert.Throws(() => zis.Read(buffer, 0, 1), "Trying to read the stream should throw"); } /// @@ -510,50 +500,44 @@ public void ShouldBeAbleToReadEntriesWithInvalidFileNames() [Category("Zip")] public void AddingAnAESEntryWithNoPasswordShouldThrow() { - using (var memoryStream = new MemoryStream()) - { - using (var outStream = new ZipOutputStream(memoryStream)) - { - var newEntry = new ZipEntry("test") { AESKeySize = 256 }; + using var memoryStream = new MemoryStream(); + using var outStream = new ZipOutputStream(memoryStream); + var newEntry = new ZipEntry("test") { AESKeySize = 256 }; - Assert.Throws(() => outStream.PutNextEntry(newEntry)); - } - } + Assert.Throws(() => outStream.PutNextEntry(newEntry)); } [Test] [Category("Zip")] public void ShouldThrowDescriptiveExceptionOnUncompressedDescriptorEntry() { - using (var ms = new MemoryStreamWithoutSeek()) + using var ms = new MemoryStreamWithoutSeek(); + using (var zos = new ZipOutputStream(ms)) { - using (var zos = new ZipOutputStream(ms)) - { - zos.IsStreamOwner = false; - var entry = new ZipEntry("testentry"); - entry.CompressionMethod = CompressionMethod.Stored; - entry.Flags |= (int)GeneralBitFlags.Descriptor; - zos.PutNextEntry(entry); - zos.Write(new byte[1], 0, 1); - zos.CloseEntry(); - } + zos.IsStreamOwner = false; + var entry = new ZipEntry("testentry"); + entry.CompressionMethod = CompressionMethod.Stored; + entry.Flags |= (int)GeneralBitFlags.Descriptor; + zos.PutNextEntry(entry); + zos.Write(new byte[1], 0, 1); + zos.CloseEntry(); + } - // Patch the Compression Method, since ZipOutputStream automatically changes it to Deflate when descriptors are used - ms.Seek(8, SeekOrigin.Begin); - ms.WriteByte((byte)CompressionMethod.Stored); - ms.Seek(0, SeekOrigin.Begin); + // Patch the Compression Method, since ZipOutputStream automatically changes it to Deflate when descriptors are used + ms.Seek(8, SeekOrigin.Begin); + ms.WriteByte((byte)CompressionMethod.Stored); + ms.Seek(0, SeekOrigin.Begin); - using (var zis = new ZipInputStream(ms)) - { - zis.IsStreamOwner = false; - var buf = new byte[32]; - zis.GetNextEntry(); + using (var zis = new ZipInputStream(ms)) + { + zis.IsStreamOwner = false; + var buf = new byte[32]; + zis.GetNextEntry(); - Assert.Throws(typeof(StreamUnsupportedException), () => - { - zis.Read(buf, 0, buf.Length); - }); - } + Assert.Throws(typeof(StreamUnsupportedException), () => + { + zis.Read(buf, 0, buf.Length); + }); } } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index a9a7583fc..f2b3e7859 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -238,30 +238,30 @@ public void Zip64Offset() [Category("Zip")] public void BasicEncryption() { - const string TestValue = "0001000"; + const string testValue = "0001000"; var memStream = new MemoryStream(); - using (ZipFile f = new ZipFile(memStream)) + using (var zf = new ZipFile(memStream)) { - f.IsStreamOwner = false; - f.Password = "Hello"; + zf.IsStreamOwner = false; + zf.Password = "Hello"; - var m = new StringMemoryDataSource(TestValue); - f.BeginUpdate(new MemoryArchiveStorage()); - f.Add(m, "a.dat"); - f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true), "Archive test should pass"); + var m = new StringMemoryDataSource(testValue); + zf.BeginUpdate(new MemoryArchiveStorage()); + zf.Add(m, "a.dat"); + zf.CommitUpdate(); + Assert.IsTrue(zf.TestArchive(testData: true), "Archive test should pass"); } - using (ZipFile g = new ZipFile(memStream)) + using (var zf = new ZipFile(memStream)) { - g.Password = "Hello"; - ZipEntry ze = g[0]; + zf.Password = "Hello"; + var ze = zf[0]; Assert.IsTrue(ze.IsCrypted, "Entry should be encrypted"); - using (StreamReader r = new StreamReader(g.GetInputStream(0))) + using (var r = new StreamReader(zf.GetInputStream(entryIndex: 0))) { - string data = r.ReadToEnd(); - Assert.AreEqual(TestValue, data); + var data = r.ReadToEnd(); + Assert.AreEqual(testValue, data); } } } @@ -271,38 +271,38 @@ public void BasicEncryption() [Category("CreatesTempFile")] public void BasicEncryptionToDisk() { - const string TestValue = "0001000"; - string tempFile = GetTempFilePath(); + const string testValue = "0001000"; + var tempFile = GetTempFilePath(); Assert.IsNotNull(tempFile, "No permission to execute this test?"); tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); - using (ZipFile f = ZipFile.Create(tempFile)) + using (var zf = ZipFile.Create(tempFile)) { - f.Password = "Hello"; + zf.Password = "Hello"; - var m = new StringMemoryDataSource(TestValue); - f.BeginUpdate(); - f.Add(m, "a.dat"); - f.CommitUpdate(); + var m = new StringMemoryDataSource(testValue); + zf.BeginUpdate(); + zf.Add(m, "a.dat"); + zf.CommitUpdate(); } - using (ZipFile f = new ZipFile(tempFile)) + using (var zf = new ZipFile(tempFile)) { - f.Password = "Hello"; - Assert.IsTrue(f.TestArchive(true), "Archive test should pass"); + zf.Password = "Hello"; + Assert.IsTrue(zf.TestArchive(testData: true), "Archive test should pass"); } - using (ZipFile g = new ZipFile(tempFile)) + using (var zf = new ZipFile(tempFile)) { - g.Password = "Hello"; - ZipEntry ze = g[0]; + zf.Password = "Hello"; + ZipEntry ze = zf[0]; Assert.IsTrue(ze.IsCrypted, "Entry should be encrypted"); - using (StreamReader r = new StreamReader(g.GetInputStream(0))) + using (var r = new StreamReader(zf.GetInputStream(entryIndex: 0))) { - string data = r.ReadToEnd(); - Assert.AreEqual(TestValue, data); + var data = r.ReadToEnd(); + Assert.AreEqual(testValue, data); } } @@ -313,14 +313,14 @@ public void BasicEncryptionToDisk() [Category("Zip")] public void AddEncryptedEntriesToExistingArchive() { - const string TestValue = "0001000"; + const string testValue = "0001000"; var memStream = new MemoryStream(); using (ZipFile f = new ZipFile(memStream)) { f.IsStreamOwner = false; f.UseZip64 = UseZip64.Off; - var m = new StringMemoryDataSource(TestValue); + var m = new StringMemoryDataSource(testValue); f.BeginUpdate(new MemoryArchiveStorage()); f.Add(m, "a.dat"); f.CommitUpdate(); @@ -335,10 +335,10 @@ public void AddEncryptedEntriesToExistingArchive() using (StreamReader r = new StreamReader(g.GetInputStream(0))) { string data = r.ReadToEnd(); - Assert.AreEqual(TestValue, data); + Assert.AreEqual(testValue, data); } - var n = new StringMemoryDataSource(TestValue); + var n = new StringMemoryDataSource(testValue); g.Password = "Axolotyl"; g.UseZip64 = UseZip64.Off; @@ -353,7 +353,7 @@ public void AddEncryptedEntriesToExistingArchive() using (StreamReader r = new StreamReader(g.GetInputStream(0))) { string data = r.ReadToEnd(); - Assert.AreEqual(TestValue, data); + Assert.AreEqual(testValue, data); } } } @@ -684,28 +684,25 @@ public void CreateEmptyArchive() [Category("CreatesTempFile")] public void CreateArchiveWithNoCompression() { - - using (var sourceFile = Utils.GetDummyFile()) - using (var zipFile = Utils.GetDummyFile(0)) + using var sourceFile = Utils.GetDummyFile(); + using var zipFile = Utils.GetDummyFile(0); + var inputContent = File.ReadAllText(sourceFile); + using (var zf = ZipFile.Create(zipFile)) { - var inputContent = File.ReadAllText(sourceFile.Filename); - using (ZipFile f = ZipFile.Create(zipFile.Filename)) - { - f.BeginUpdate(); - f.Add(sourceFile.Filename, CompressionMethod.Stored); - f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); - f.Close(); - } + zf.BeginUpdate(); + zf.Add(sourceFile, CompressionMethod.Stored); + zf.CommitUpdate(); + Assert.IsTrue(zf.TestArchive(testData: true)); + zf.Close(); + } - using (ZipFile f = new ZipFile(zipFile.Filename)) + using (var zf = new ZipFile(zipFile)) + { + Assert.AreEqual(1, zf.Count); + using (var sr = new StreamReader(zf.GetInputStream(zf[0]))) { - Assert.AreEqual(1, f.Count); - using (var sr = new StreamReader(f.GetInputStream(f[0]))) - { - var outputContent = sr.ReadToEnd(); - Assert.AreEqual(inputContent, outputContent, "extracted content does not match source content"); - } + var outputContent = sr.ReadToEnd(); + Assert.AreEqual(inputContent, outputContent, "extracted content does not match source content"); } } } @@ -1009,45 +1006,40 @@ public void Crypto_AddEncryptedEntryToExistingArchiveDirect() [Category("Unicode")] public void UnicodeNames() { - using (var memStream = new MemoryStream()) + using var memStream = new MemoryStream(); + using (var f = new ZipFile(memStream)) { - using (ZipFile f = new ZipFile(memStream)) - { - f.IsStreamOwner = false; - - f.BeginUpdate(new MemoryArchiveStorage()); - foreach ((string language, string name, _) in StringTesting.GetTestSamples()) - { - f.Add(new StringMemoryDataSource(language), name, - CompressionMethod.Deflated, true); - } - f.CommitUpdate(); + f.IsStreamOwner = false; - Assert.IsTrue(f.TestArchive(true)); - } - memStream.Seek(0, SeekOrigin.Begin); - using (var zf = new ZipFile(memStream)) + f.BeginUpdate(new MemoryArchiveStorage()); + foreach (var (language, name, _) in StringTesting.TestSamples) { - foreach (string name in StringTesting.Filenames) - { - //int index = zf.FindEntry(name, true); - var content = ""; - var index = zf.FindEntry(name, true); - var entry = zf[index]; + f.Add(new StringMemoryDataSource(language), name, + CompressionMethod.Deflated, useUnicodeText: true); + } + f.CommitUpdate(); - using (var entryStream = zf.GetInputStream(entry)) - using (var sr = new StreamReader(entryStream)) - { - content = sr.ReadToEnd(); - } + Assert.IsTrue(f.TestArchive(testData: true)); + } + memStream.Seek(0, SeekOrigin.Begin); + using (var zf = new ZipFile(memStream)) + { + foreach (var name in StringTesting.Filenames) + { + string content; + var index = zf.FindEntry(name, ignoreCase: true); + var entry = zf[index]; - //var content = + using (var entryStream = zf.GetInputStream(entry)) + using (var sr = new StreamReader(entryStream)) + { + content = sr.ReadToEnd(); + } - Console.WriteLine($"Entry #{index}: {name}, Content: {content}"); + TestContext.WriteLine($"Entry #{index}: {name}, Content: {content}"); - Assert.IsTrue(index >= 0); - Assert.AreEqual(name, entry.Name); - } + Assert.IsTrue(index >= 0); + Assert.AreEqual(name, entry.Name); } } } @@ -1463,57 +1455,28 @@ public void FileStreamNotClosedWhenNotOwner() } /// - /// Check that input stream is closed when construction fails and leaveOpen is false + /// Check that input stream is only closed when construction fails and leaveOpen is false /// [Test] [Category("Zip")] - public void StreamClosedOnError() + public void StreamClosedOnError([Values(true, false)] bool leaveOpen) { var ms = new TrackedMemoryStream(new byte[32]); Assert.IsFalse(ms.IsClosed, "Underlying stream should NOT be closed initially"); - bool blewUp = false; - try - { - using (var zipFile = new ZipFile(ms, false)) - { - Assert.Fail("Exception not thrown"); - } - } - catch + Assert.Throws(() => { - blewUp = true; - } + using var zf = new ZipFile(ms, leaveOpen); + }, "Should have failed to load the file"); - Assert.IsTrue(blewUp, "Should have failed to load the file"); - Assert.IsTrue(ms.IsClosed, "Underlying stream should be closed"); - } - - /// - /// Check that input stream is not closed when construction fails and leaveOpen is true - /// - [Test] - [Category("Zip")] - public void StreamNotClosedOnError() - { - var ms = new TrackedMemoryStream(new byte[32]); - - Assert.IsFalse(ms.IsClosed, "Underlying stream should NOT be closed initially"); - bool blewUp = false; - try + if (leaveOpen) { - using (var zipFile = new ZipFile(ms, true)) - { - Assert.Fail("Exception not thrown"); - } + Assert.IsFalse(ms.IsClosed, "Underlying stream should NOT be closed"); } - catch + else { - blewUp = true; + Assert.IsTrue(ms.IsClosed, "Underlying stream should be closed"); } - - Assert.IsTrue(blewUp, "Should have failed to load the file"); - Assert.IsFalse(ms.IsClosed, "Underlying stream should NOT be closed"); } [Test] @@ -1586,17 +1549,15 @@ public void HostSystemPersistedFromZipFile() public void AddingAnAESEncryptedEntryShouldThrow() { var memStream = new MemoryStream(); - using (ZipFile zof = new ZipFile(memStream)) + using var zof = new ZipFile(memStream); + var entry = new ZipEntry("test") { - var entry = new ZipEntry("test") - { - AESKeySize = 256 - }; + AESKeySize = 256, + }; - zof.BeginUpdate(); - var exception = Assert.Throws(() => zof.Add(new StringMemoryDataSource("foo"), entry)); - Assert.That(exception.Message, Is.EqualTo("Creation of AES encrypted entries is not supported")); - } + zof.BeginUpdate(); + var exception = Assert.Throws(() => zof.Add(new StringMemoryDataSource("foo"), entry)); + Assert.That(exception?.Message, Is.EqualTo("Creation of AES encrypted entries is not supported")); } /// @@ -1608,35 +1569,33 @@ public void AddingAnAESEncryptedEntryShouldThrow() public void AddFileWithAlternateName() { // Create a unique name that will be different from the file name - string fileName = Guid.NewGuid().ToString(); + var fileName = Utils.GetDummyFileName(); - using (var sourceFile = Utils.GetDummyFile()) - using (var outputFile = Utils.GetDummyFile(0)) + using var sourceFile = Utils.GetDummyFile(size: 16); + using var outputFile = Utils.GetTempFile(); + var inputContent = File.ReadAllText(sourceFile); + using (var zf = ZipFile.Create(outputFile)) { - var inputContent = File.ReadAllText(sourceFile.Filename); - using (ZipFile f = ZipFile.Create(outputFile.Filename)) - { - f.BeginUpdate(); + zf.BeginUpdate(); - // Add a file with the unique display name - f.Add(sourceFile.Filename, fileName); + // Add a file with the unique display name + zf.Add(sourceFile, fileName); - f.CommitUpdate(); - f.Close(); - } + zf.CommitUpdate(); + zf.Close(); + } - using (ZipFile zipFile = new ZipFile(outputFile.Filename)) - { - Assert.That(zipFile.Count, Is.EqualTo(1)); + using (var zipFile = new ZipFile(outputFile)) + { + Assert.That(zipFile.Count, Is.EqualTo(1)); - var fileEntry = zipFile.GetEntry(fileName); - Assert.That(fileEntry, Is.Not.Null); + var fileEntry = zipFile.GetEntry(fileName); + Assert.That(fileEntry, Is.Not.Null); - using (var sr = new StreamReader(zipFile.GetInputStream(fileEntry))) - { - var outputContent = sr.ReadToEnd(); - Assert.AreEqual(inputContent, outputContent, "extracted content does not match source content"); - } + using (var sr = new StreamReader(zipFile.GetInputStream(fileEntry))) + { + var outputContent = sr.ReadToEnd(); + Assert.AreEqual(inputContent, outputContent, "extracted content does not match source content"); } } } @@ -1713,7 +1672,7 @@ public void ZipWithBZip2Compression(bool encryptEntries) [Category("Zip")] public void ShouldReadBZip2ZipCreatedBy7Zip() { - const string BZip2CompressedZipCreatedBy7Zip = + const string bZip2CompressedZipCreatedBy7Zip = "UEsDBC4AAAAMAIa50U4/rHf5qwAAAK8AAAAJAAAASGVsbG8udHh0QlpoOTFBWSZTWTL8pwYAA" + "BWfgEhlUAAiLUgQP+feMCAAiCKaeiaBobU9JiaAMGmoak9GmRNqPUDQ9T1PQsz/t9B6YvEdvF" + "5dhwXzGE1ooO41A6TtATBEFxFUq6trGtUcSJDyWWWj/S2VwY15fy3IqHi3hHUS+K76zdoDzQa" + @@ -1721,26 +1680,20 @@ public void ShouldReadBZip2ZipCreatedBy7Zip() "AAwAhrnRTj+sd/mrAAAArwAAAAkAJAAAAAAAAAAgAAAAAAAAAEhlbGxvLnR4dAoAIAAAAAAAA" + "QAYAO97MLZZJdUB73swtlkl1QEK0UTFWCXVAVBLBQYAAAAAAQABAFsAAADSAAAAAAA="; - const string OriginalText = + const string originalText = "SharpZipLib (#ziplib, formerly NZipLib) is a compression library that supports Zip files using both stored and deflate compression methods, PKZIP 2.0 style and AES encryption."; - var fileBytes = System.Convert.FromBase64String(BZip2CompressedZipCreatedBy7Zip); + var fileBytes = Convert.FromBase64String(bZip2CompressedZipCreatedBy7Zip); - using (var input = new MemoryStream(fileBytes, false)) - { - using (ZipFile f = new ZipFile(input)) - { - var entry = f.GetEntry("Hello.txt"); - Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Compression method should be BZip2"); - Assert.That(entry.Version, Is.EqualTo(ZipConstants.VersionBZip2), "Entry version should be 46"); + using var input = new MemoryStream(fileBytes, writable: false); + using var zf = new ZipFile(input); + var entry = zf.GetEntry("Hello.txt"); + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Compression method should be BZip2"); + Assert.That(entry.Version, Is.EqualTo(ZipConstants.VersionBZip2), "Entry version should be 46"); - using (var reader = new StreamReader(f.GetInputStream(entry))) - { - string contents = reader.ReadToEnd(); - Assert.That(contents, Is.EqualTo(OriginalText), "extract string must match original string"); - } - } - } + using var reader = new StreamReader(zf.GetInputStream(entry)); + var contents = reader.ReadToEnd(); + Assert.That(contents, Is.EqualTo(originalText), "extract string must match original string"); } /// @@ -1750,7 +1703,7 @@ public void ShouldReadBZip2ZipCreatedBy7Zip() [Category("Zip")] public void ShouldReadAESBZip2ZipCreatedBy7Zip() { - const string BZip2CompressedZipCreatedBy7Zip = + const string bZip2CompressedZipCreatedBy7Zip = "UEsDBDMAAQBjAIa50U4AAAAAxwAAAK8AAAAJAAsASGVsbG8udHh0AZkHAAIAQUUDDAAYg6jqf" + "kvZClVMOtgmqKT0/8I9fMPgo96myxw9hLQUhKj1Qczi3fT7QIhAnAKU+u03nA8rCKGWmDI5Qz" + "qPREy95boQVDPwmwEsWksv3GAWzMfzZUhmB/TgIJlA34a4yP0f2ucy3/QCQYo8QcHjBtjWX5b" + @@ -1759,30 +1712,24 @@ public void ShouldReadAESBZip2ZipCreatedBy7Zip() "wAAAAkALwAAAAAAAAAgAAAAAAAAAEhlbGxvLnR4dAoAIAAAAAAAAQAYAO97MLZZJdUBYdnjul" + "kl1QEK0UTFWCXVAQGZBwACAEFFAwwAUEsFBgAAAAABAAEAZgAAAPkAAAAAAA=="; - const string OriginalText = + const string originalText = "SharpZipLib (#ziplib, formerly NZipLib) is a compression library that supports Zip files using both stored and deflate compression methods, PKZIP 2.0 style and AES encryption."; - var fileBytes = System.Convert.FromBase64String(BZip2CompressedZipCreatedBy7Zip); + var fileBytes = Convert.FromBase64String(bZip2CompressedZipCreatedBy7Zip); - using (var input = new MemoryStream(fileBytes, false)) - { - using (ZipFile f = new ZipFile(input)) - { - f.Password = "password"; + using var input = new MemoryStream(fileBytes, writable: false); + using var zf = new ZipFile(input); + zf.Password = "password"; - var entry = f.GetEntry("Hello.txt"); - Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Compression method should be BZip2"); - Assert.That(entry.Version, Is.EqualTo(ZipConstants.VERSION_AES), "Entry version should be 51"); - Assert.That(entry.IsCrypted, Is.True, "Entry should be encrypted"); - Assert.That(entry.AESKeySize, Is.EqualTo(256), "AES Keysize should be 256"); + var entry = zf.GetEntry("Hello.txt"); + Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.BZip2), "Compression method should be BZip2"); + Assert.That(entry.Version, Is.EqualTo(ZipConstants.VERSION_AES), "Entry version should be 51"); + Assert.That(entry.IsCrypted, Is.True, "Entry should be encrypted"); + Assert.That(entry.AESKeySize, Is.EqualTo(256), "AES Keysize should be 256"); - using (var reader = new StreamReader(f.GetInputStream(entry))) - { - string contents = reader.ReadToEnd(); - Assert.That(contents, Is.EqualTo(OriginalText), "extract string must match original string"); - } - } - } + using var reader = new StreamReader(zf.GetInputStream(entry)); + var contents = reader.ReadToEnd(); + Assert.That(contents, Is.EqualTo(originalText), "extract string must match original string"); } /// From d34e5c910d29f1527bc4248781598c4208af81ee Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 9 Oct 2021 17:16:40 +0100 Subject: [PATCH 129/162] fix(zip): use ushort for ITaggedData.TagID (#669) --- src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs index 4e075dc8d..12e29bb3e 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs @@ -15,7 +15,7 @@ public interface ITaggedData /// /// Get the ID for this tagged data value. /// - short TagID { get; } + ushort TagID { get; } /// /// Set the contents of this instance from the data passed. @@ -41,7 +41,7 @@ public class RawTaggedData : ITaggedData /// Initialise a new instance. /// /// The tag ID. - public RawTaggedData(short tag) + public RawTaggedData(ushort tag) { _tag = tag; } @@ -51,7 +51,7 @@ public RawTaggedData(short tag) /// /// Get the ID for this tagged data value. /// - public short TagID + public ushort TagID { get { return _tag; } set { _tag = value; } @@ -100,7 +100,7 @@ public byte[] Data /// /// The tag ID for this instance. /// - private short _tag; + private ushort _tag; private byte[] _data; @@ -139,7 +139,7 @@ public enum Flags : byte /// /// Get the ID /// - public short TagID + public ushort TagID { get { return 0x5455; } } @@ -328,7 +328,7 @@ public class NTTaggedData : ITaggedData /// /// Get the ID for this tagged data value. /// - public short TagID + public ushort TagID { get { return 10; } } From 6f7d973b9014fb29aa34f268e22f8cb3b5fe0e6b Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sat, 9 Oct 2021 17:52:20 +0100 Subject: [PATCH 130/162] chore: remove the test bootstrapper (#670) --- ICSharpCode.SharpZipLib.sln | 6 ------ ...rpCode.SharpZipLib.TestBootstrapper.csproj | 21 ------------------- .../Program.cs | 14 ------------- 3 files changed, 41 deletions(-) delete mode 100644 test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj delete mode 100644 test/ICSharpCode.SharpZipLib.TestBootstrapper/Program.cs diff --git a/ICSharpCode.SharpZipLib.sln b/ICSharpCode.SharpZipLib.sln index cab9675b5..0c4c6c5f4 100644 --- a/ICSharpCode.SharpZipLib.sln +++ b/ICSharpCode.SharpZipLib.sln @@ -15,8 +15,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.SharpZipLib", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.SharpZipLib.Tests", "test\ICSharpCode.SharpZipLib.Tests\ICSharpCode.SharpZipLib.Tests.csproj", "{82211166-9C45-4603-8E3A-2CA2EFFCBC26}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.SharpZipLib.TestBootstrapper", "test\ICSharpCode.SharpZipLib.TestBootstrapper\ICSharpCode.SharpZipLib.TestBootstrapper.csproj", "{535D7365-C5B1-4253-9233-D72D972CA851}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ICSharpCode.SharpZipLib.Benchmark", "benchmark\ICSharpCode.SharpZipLib.Benchmark\ICSharpCode.SharpZipLib.Benchmark.csproj", "{C51E638B-DDD0-48B6-A6BD-EBC4E6A104C7}" EndProject Global @@ -33,10 +31,6 @@ Global {82211166-9C45-4603-8E3A-2CA2EFFCBC26}.Debug|Any CPU.Build.0 = Debug|Any CPU {82211166-9C45-4603-8E3A-2CA2EFFCBC26}.Release|Any CPU.ActiveCfg = Release|Any CPU {82211166-9C45-4603-8E3A-2CA2EFFCBC26}.Release|Any CPU.Build.0 = Release|Any CPU - {535D7365-C5B1-4253-9233-D72D972CA851}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {535D7365-C5B1-4253-9233-D72D972CA851}.Debug|Any CPU.Build.0 = Debug|Any CPU - {535D7365-C5B1-4253-9233-D72D972CA851}.Release|Any CPU.ActiveCfg = Release|Any CPU - {535D7365-C5B1-4253-9233-D72D972CA851}.Release|Any CPU.Build.0 = Release|Any CPU {C51E638B-DDD0-48B6-A6BD-EBC4E6A104C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C51E638B-DDD0-48B6-A6BD-EBC4E6A104C7}.Debug|Any CPU.Build.0 = Debug|Any CPU {C51E638B-DDD0-48B6-A6BD-EBC4E6A104C7}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj b/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj deleted file mode 100644 index 3e3ba13d6..000000000 --- a/test/ICSharpCode.SharpZipLib.TestBootstrapper/ICSharpCode.SharpZipLib.TestBootstrapper.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - Exe - netcoreapp3.1 - - - - - - - - - - - - - - - - diff --git a/test/ICSharpCode.SharpZipLib.TestBootstrapper/Program.cs b/test/ICSharpCode.SharpZipLib.TestBootstrapper/Program.cs deleted file mode 100644 index 4a030de1f..000000000 --- a/test/ICSharpCode.SharpZipLib.TestBootstrapper/Program.cs +++ /dev/null @@ -1,14 +0,0 @@ -using NUnitLite; -using System.Reflection; - -namespace ICSharpCode.SharpZipLib.TestBootstrapper -{ - public class Program - { - private static void Main(string[] args) - { - new AutoRun(typeof(Tests.Base.InflaterDeflaterTestSuite).GetTypeInfo().Assembly) - .Execute(args); - } - } -} From e1e1a9111c6cb77ea72bd5771931c3b1defbd258 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sat, 9 Oct 2021 18:55:31 +0200 Subject: [PATCH 131/162] feat(zip): ZipOutputStream async support (#574) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cédric Luthi --- src/ICSharpCode.SharpZipLib/AssemblyInfo.cs | 3 + .../Core/ByteOrderUtils.cs | 130 ++++ .../Core/StreamUtils.cs | 37 +- .../ICSharpCode.SharpZipLib.csproj | 2 +- .../Streams/DeflaterOutputStream.cs | 87 ++- .../Zip/ZipExtraData.cs | 52 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 50 +- src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs | 597 +++++++++++++++++ .../Zip/ZipHelperStream.cs | 629 ------------------ .../Zip/ZipOutputStream.cs | 553 +++++---------- .../Base/InflaterDeflaterTests.cs | 3 +- .../Core/ByteOrderUtilsTests.cs | 137 ++++ .../ICSharpCode.SharpZipLib.Tests.csproj | 11 +- .../TestSupport/Utils.cs | 8 + .../TestSupport/ZipTesting.cs | 47 +- .../Zip/ZipFileHandling.cs | 5 +- .../Zip/ZipStreamAsyncTests.cs | 102 +++ 17 files changed, 1360 insertions(+), 1093 deletions(-) create mode 100644 src/ICSharpCode.SharpZipLib/AssemblyInfo.cs create mode 100644 src/ICSharpCode.SharpZipLib/Core/ByteOrderUtils.cs create mode 100644 src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs create mode 100644 test/ICSharpCode.SharpZipLib.Tests/Core/ByteOrderUtilsTests.cs create mode 100644 test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs diff --git a/src/ICSharpCode.SharpZipLib/AssemblyInfo.cs b/src/ICSharpCode.SharpZipLib/AssemblyInfo.cs new file mode 100644 index 000000000..8f8e62016 --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("ICSharpCode.SharpZipLib.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b9a14ea8fc9d7599e0e82a1292a23103f0210e2f928a0f466963af23fffadba59dcc8c9e26ecd114d7c0b4179e4bc93b1656b7ee2d4a67dd7c1992653e0d9cc534f7914b6f583b022e0a7aa8a430f407932f9a6806f0fc64d61e78d5ae01aa8f8233196719d44da2c50a2d1cfa3f7abb7487b3567a4f0456aa6667154c6749b1")] diff --git a/src/ICSharpCode.SharpZipLib/Core/ByteOrderUtils.cs b/src/ICSharpCode.SharpZipLib/Core/ByteOrderUtils.cs new file mode 100644 index 000000000..a2e30da7f --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Core/ByteOrderUtils.cs @@ -0,0 +1,130 @@ +using System.IO; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using CT = System.Threading.CancellationToken; + +// ReSharper disable MemberCanBePrivate.Global +// ReSharper disable InconsistentNaming + +namespace ICSharpCode.SharpZipLib.Core +{ + internal static class ByteOrderStreamExtensions + { + internal static byte[] SwappedBytes(ushort value) => new[] {(byte)value, (byte)(value >> 8)}; + internal static byte[] SwappedBytes(short value) => new[] {(byte)value, (byte)(value >> 8)}; + internal static byte[] SwappedBytes(uint value) => new[] {(byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24)}; + internal static byte[] SwappedBytes(int value) => new[] {(byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24)}; + + internal static byte[] SwappedBytes(long value) => new[] { + (byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24), + (byte)(value >> 32), (byte)(value >> 40), (byte)(value >> 48), (byte)(value >> 56) + }; + + internal static byte[] SwappedBytes(ulong value) => new[] { + (byte)value, (byte)(value >> 8), (byte)(value >> 16), (byte)(value >> 24), + (byte)(value >> 32), (byte)(value >> 40), (byte)(value >> 48), (byte)(value >> 56) + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static long SwappedS64(byte[] bytes) => ( + (long)bytes[0] << 0 | (long)bytes[1] << 8 | (long)bytes[2] << 16 | (long)bytes[3] << 24 | + (long)bytes[4] << 32 | (long)bytes[5] << 40 | (long)bytes[6] << 48 | (long)bytes[7] << 56); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ulong SwappedU64(byte[] bytes) => ( + (ulong)bytes[0] << 0 | (ulong)bytes[1] << 8 | (ulong)bytes[2] << 16 | (ulong)bytes[3] << 24 | + (ulong)bytes[4] << 32 | (ulong)bytes[5] << 40 | (ulong)bytes[6] << 48 | (ulong)bytes[7] << 56); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static int SwappedS32(byte[] bytes) => bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static uint SwappedU32(byte[] bytes) => (uint) SwappedS32(bytes); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static short SwappedS16(byte[] bytes) => (short)(bytes[0] | bytes[1] << 8); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ushort SwappedU16(byte[] bytes) => (ushort) SwappedS16(bytes); + + internal static byte[] ReadBytes(this Stream stream, int count) + { + var bytes = new byte[count]; + var remaining = count; + while (remaining > 0) + { + var bytesRead = stream.Read(bytes, count - remaining, remaining); + if (bytesRead < 1) throw new EndOfStreamException(); + remaining -= bytesRead; + } + + return bytes; + } + + /// Read an unsigned short in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadLEShort(this Stream stream) => SwappedS16(ReadBytes(stream, 2)); + + /// Read an int in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int ReadLEInt(this Stream stream) => SwappedS32(ReadBytes(stream, 4)); + + /// Read a long in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long ReadLELong(this Stream stream) => SwappedS64(ReadBytes(stream, 8)); + + /// Write an unsigned short in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteLEShort(this Stream stream, int value) => stream.Write(SwappedBytes(value), 0, 2); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task WriteLEShortAsync(this Stream stream, int value, CT ct) + => await stream.WriteAsync(SwappedBytes(value), 0, 2, ct); + + /// Write a ushort in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteLEUshort(this Stream stream, ushort value) => stream.Write(SwappedBytes(value), 0, 2); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task WriteLEUshortAsync(this Stream stream, ushort value, CT ct) + => await stream.WriteAsync(SwappedBytes(value), 0, 2, ct); + + /// Write an int in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteLEInt(this Stream stream, int value) => stream.Write(SwappedBytes(value), 0, 4); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task WriteLEIntAsync(this Stream stream, int value, CT ct) + => await stream.WriteAsync(SwappedBytes(value), 0, 4, ct); + + /// Write a uint in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteLEUint(this Stream stream, uint value) => stream.Write(SwappedBytes(value), 0, 4); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task WriteLEUintAsync(this Stream stream, uint value, CT ct) + => await stream.WriteAsync(SwappedBytes(value), 0, 4, ct); + + /// Write a long in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteLELong(this Stream stream, long value) => stream.Write(SwappedBytes(value), 0, 8); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task WriteLELongAsync(this Stream stream, long value, CT ct) + => await stream.WriteAsync(SwappedBytes(value), 0, 8, ct); + + /// Write a ulong in little endian byte order. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static void WriteLEUlong(this Stream stream, ulong value) => stream.Write(SwappedBytes(value), 0, 8); + + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static async Task WriteLEUlongAsync(this Stream stream, ulong value, CT ct) + => await stream.WriteAsync(SwappedBytes(value), 0, 8, ct); + } +} diff --git a/src/ICSharpCode.SharpZipLib/Core/StreamUtils.cs b/src/ICSharpCode.SharpZipLib/Core/StreamUtils.cs index 6d0d9b304..47de6e26e 100644 --- a/src/ICSharpCode.SharpZipLib/Core/StreamUtils.cs +++ b/src/ICSharpCode.SharpZipLib/Core/StreamUtils.cs @@ -1,12 +1,14 @@ using System; using System.IO; +using System.Threading; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Core { /// /// Provides simple " utilities. /// - public sealed class StreamUtils + public static class StreamUtils { /// /// Read from a ensuring all the required data is read. @@ -14,7 +16,7 @@ public sealed class StreamUtils /// The stream to read. /// The buffer to fill. /// - static public void ReadFully(Stream stream, byte[] buffer) + public static void ReadFully(Stream stream, byte[] buffer) { ReadFully(stream, buffer, 0, buffer.Length); } @@ -29,7 +31,7 @@ static public void ReadFully(Stream stream, byte[] buffer) /// Required parameter is null /// and or are invalid. /// End of stream is encountered before all the data has been read. - static public void ReadFully(Stream stream, byte[] buffer, int offset, int count) + public static void ReadFully(Stream stream, byte[] buffer, int offset, int count) { if (stream == null) { @@ -73,7 +75,7 @@ static public void ReadFully(Stream stream, byte[] buffer, int offset, int count /// The number of bytes of data to store. /// Required parameter is null /// and or are invalid. - static public int ReadRequestedBytes(Stream stream, byte[] buffer, int offset, int count) + public static int ReadRequestedBytes(Stream stream, byte[] buffer, int offset, int count) { if (stream == null) { @@ -118,7 +120,7 @@ static public int ReadRequestedBytes(Stream stream, byte[] buffer, int offset, i /// The stream to source data from. /// The stream to write data to. /// The buffer to use during copying. - static public void Copy(Stream source, Stream destination, byte[] buffer) + public static void Copy(Stream source, Stream destination, byte[] buffer) { if (source == null) { @@ -169,7 +171,7 @@ static public void Copy(Stream source, Stream destination, byte[] buffer) /// The source for this event. /// The name to use with the event. /// This form is specialised for use within #Zip to support events during archive operations. - static public void Copy(Stream source, Stream destination, + public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name) { Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1); @@ -188,7 +190,7 @@ static public void Copy(Stream source, Stream destination, /// A predetermined fixed target value to use with progress updates. /// If the value is negative the target is calculated by looking at the stream. /// This form is specialised for use within #Zip to support events during archive operations. - static public void Copy(Stream source, Stream destination, + public static void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name, long fixedTarget) @@ -272,13 +274,22 @@ static public void Copy(Stream source, Stream destination, progressHandler(sender, args); } } - - /// - /// Initialise an instance of - /// - private StreamUtils() + + internal static async Task WriteProcToStreamAsync(this Stream targetStream, MemoryStream bufferStream, Action writeProc, CancellationToken ct) { - // Do nothing. + bufferStream.SetLength(0); + writeProc(bufferStream); + bufferStream.Position = 0; + await bufferStream.CopyToAsync(targetStream, 81920, ct); + bufferStream.SetLength(0); + } + + internal static async Task WriteProcToStreamAsync(this Stream targetStream, Action writeProc, CancellationToken ct) + { + using (var ms = new MemoryStream()) + { + await WriteProcToStreamAsync(targetStream, ms, writeProc, ct); + } } } } diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index ca37ba1ae..066c4fb43 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -40,5 +40,5 @@ Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.3 for mor images - + diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs index b6d4025d1..fd4bb47af 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs @@ -2,6 +2,8 @@ using System; using System.IO; using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { @@ -105,10 +107,7 @@ public virtual void Finish() break; } - if (cryptoTransform_ != null) - { - EncryptBlock(buffer_, 0, len); - } + EncryptBlock(buffer_, 0, len); baseOutputStream_.Write(buffer_, 0, len); } @@ -131,6 +130,47 @@ public virtual void Finish() } } + /// + /// Finishes the stream by calling finish() on the deflater. + /// + /// The that can be used to cancel the operation. + /// + /// Not all input is deflated + /// + public virtual async Task FinishAsync(CancellationToken ct) + { + deflater_.Finish(); + while (!deflater_.IsFinished) + { + int len = deflater_.Deflate(buffer_, 0, buffer_.Length); + if (len <= 0) + { + break; + } + + EncryptBlock(buffer_, 0, len); + + await baseOutputStream_.WriteAsync(buffer_, 0, len, ct); + } + + if (!deflater_.IsFinished) + { + throw new SharpZipBaseException("Can't deflate all input?"); + } + + await baseOutputStream_.FlushAsync(ct); + + if (cryptoTransform_ != null) + { + if (cryptoTransform_ is ZipAESTransform) + { + AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); + } + cryptoTransform_.Dispose(); + cryptoTransform_ = null; + } + } + /// /// Gets or sets a flag indicating ownership of underlying stream. /// When the flag is true will close the underlying stream also. @@ -177,6 +217,7 @@ public bool CanPatchEntries /// protected void EncryptBlock(byte[] buffer, int offset, int length) { + if(cryptoTransform_ is null) return; cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0); } @@ -204,10 +245,8 @@ private void Deflate(bool flushing) { break; } - if (cryptoTransform_ != null) - { - EncryptBlock(buffer_, 0, deflateCount); - } + + EncryptBlock(buffer_, 0, deflateCount); baseOutputStream_.Write(buffer_, 0, deflateCount); } @@ -369,6 +408,38 @@ protected override void Dispose(bool disposing) } } +#if NETSTANDARD2_1 + /// + /// Calls and closes the underlying + /// stream when is true. + /// + public override async ValueTask DisposeAsync() + { + if (!isClosed_) + { + isClosed_ = true; + + try + { + await FinishAsync(CancellationToken.None); + if (cryptoTransform_ != null) + { + GetAuthCodeIfAES(); + cryptoTransform_.Dispose(); + cryptoTransform_ = null; + } + } + finally + { + if (IsStreamOwner) + { + await baseOutputStream_.DisposeAsync(); + } + } + } + } +#endif + /// /// Get the Auth code for AES encrypted entries /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs index 12e29bb3e..cc2e74490 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipExtraData.cs @@ -153,16 +153,15 @@ public ushort TagID public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { // bit 0 if set, modification time is present // bit 1 if set, access time is present // bit 2 if set, creation time is present - _flags = (Flags)helperStream.ReadByte(); + _flags = (Flags)ms.ReadByte(); if (((_flags & Flags.ModificationTime) != 0)) { - int iTime = helperStream.ReadLEInt(); + int iTime = ms.ReadLEInt(); _modificationTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); @@ -173,7 +172,7 @@ public void SetData(byte[] data, int index, int count) if ((_flags & Flags.AccessTime) != 0) { - int iTime = helperStream.ReadLEInt(); + int iTime = ms.ReadLEInt(); _lastAccessTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); @@ -181,7 +180,7 @@ public void SetData(byte[] data, int index, int count) if ((_flags & Flags.CreateTime) != 0) { - int iTime = helperStream.ReadLEInt(); + int iTime = ms.ReadLEInt(); _createTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); @@ -196,27 +195,25 @@ public void SetData(byte[] data, int index, int count) public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { - helperStream.IsStreamOwner = false; - helperStream.WriteByte((byte)_flags); // Flags + ms.WriteByte((byte)_flags); // Flags if ((_flags & Flags.ModificationTime) != 0) { TimeSpan span = _modificationTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; - helperStream.WriteLEInt(seconds); + ms.WriteLEInt(seconds); } if ((_flags & Flags.AccessTime) != 0) { TimeSpan span = _lastAccessTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; - helperStream.WriteLEInt(seconds); + ms.WriteLEInt(seconds); } if ((_flags & Flags.CreateTime) != 0) { TimeSpan span = _createTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; - helperStream.WriteLEInt(seconds); + ms.WriteLEInt(seconds); } return ms.ToArray(); } @@ -342,24 +339,23 @@ public ushort TagID public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { - helperStream.ReadLEInt(); // Reserved - while (helperStream.Position < helperStream.Length) + ms.ReadLEInt(); // Reserved + while (ms.Position < ms.Length) { - int ntfsTag = helperStream.ReadLEShort(); - int ntfsLength = helperStream.ReadLEShort(); + int ntfsTag = ms.ReadLEShort(); + int ntfsLength = ms.ReadLEShort(); if (ntfsTag == 1) { if (ntfsLength >= 24) { - long lastModificationTicks = helperStream.ReadLELong(); + long lastModificationTicks = ms.ReadLELong(); _lastModificationTime = DateTime.FromFileTimeUtc(lastModificationTicks); - long lastAccessTicks = helperStream.ReadLELong(); + long lastAccessTicks = ms.ReadLELong(); _lastAccessTime = DateTime.FromFileTimeUtc(lastAccessTicks); - long createTimeTicks = helperStream.ReadLELong(); + long createTimeTicks = ms.ReadLELong(); _createTime = DateTime.FromFileTimeUtc(createTimeTicks); } break; @@ -367,7 +363,7 @@ public void SetData(byte[] data, int index, int count) else { // An unknown NTFS tag so simply skip it. - helperStream.Seek(ntfsLength, SeekOrigin.Current); + ms.Seek(ntfsLength, SeekOrigin.Current); } } } @@ -380,15 +376,13 @@ public void SetData(byte[] data, int index, int count) public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) - { - helperStream.IsStreamOwner = false; - helperStream.WriteLEInt(0); // Reserved - helperStream.WriteLEShort(1); // Tag - helperStream.WriteLEShort(24); // Length = 3 x 8. - helperStream.WriteLELong(_lastModificationTime.ToFileTimeUtc()); - helperStream.WriteLELong(_lastAccessTime.ToFileTimeUtc()); - helperStream.WriteLELong(_createTime.ToFileTimeUtc()); + { + ms.WriteLEInt(0); // Reserved + ms.WriteLEShort(1); // Tag + ms.WriteLEShort(24); // Length = 3 x 8. + ms.WriteLELong(_lastModificationTime.ToFileTimeUtc()); + ms.WriteLELong(_lastAccessTime.ToFileTimeUtc()); + ms.WriteLELong(_createTime.ToFileTimeUtc()); return ms.ToArray(); } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 3bd66ffeb..a07b19f0c 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1003,10 +1003,8 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl if ((this[entryIndex].Flags & (int)GeneralBitFlags.Descriptor) != 0) { - var helper = new ZipHelperStream(baseStream_); var data = new DescriptorData(); - helper.ReadDataDescriptor(this[entryIndex].LocalHeaderRequiresZip64, data); - + ZipFormat.ReadDataDescriptor(baseStream_, this[entryIndex].LocalHeaderRequiresZip64, data); if (checkCRC && this[entryIndex].Crc != data.Crc) { status.AddError(); @@ -1582,10 +1580,7 @@ public void CommitUpdate() if (entries_.Length == 0) { byte[] theComment = (newComment_ != null) ? newComment_.RawComment : ZipStrings.ConvertToArray(comment_); - using (ZipHelperStream zhs = new ZipHelperStream(baseStream_)) - { - zhs.WriteEndOfCentralDirectory(0, 0, 0, theComment); - } + ZipFormat.WriteEndOfCentralDirectory(baseStream_, 0, 0, 0, theComment); } } } @@ -2728,8 +2723,7 @@ private void AddEntry(ZipFile workFile, ZipUpdate update) if ((update.OutEntry.Flags & (int)GeneralBitFlags.Descriptor) == (int)GeneralBitFlags.Descriptor) { - var helper = new ZipHelperStream(workFile.baseStream_); - helper.WriteDataDescriptor(update.OutEntry); + ZipFormat.WriteDataDescriptor(workFile.baseStream_, update.OutEntry); } } } @@ -2866,15 +2860,11 @@ private void UpdateCommentOnly() { long baseLength = baseStream_.Length; - ZipHelperStream updateFile = null; + Stream updateFile; if (archiveStorage_.UpdateMode == FileUpdateMode.Safe) { - Stream copyStream = archiveStorage_.MakeTemporaryCopy(baseStream_); - updateFile = new ZipHelperStream(copyStream) - { - IsStreamOwner = true - }; + updateFile = archiveStorage_.MakeTemporaryCopy(baseStream_); baseStream_.Dispose(); baseStream_ = null; @@ -2891,21 +2881,21 @@ private void UpdateCommentOnly() // Need to tidy up the archive storage interface and contract basically. baseStream_ = archiveStorage_.OpenForDirectUpdate(baseStream_); - updateFile = new ZipHelperStream(baseStream_); + updateFile = baseStream_; } else { baseStream_.Dispose(); baseStream_ = null; - updateFile = new ZipHelperStream(Name); + updateFile = new FileStream(Name, FileMode.Open, FileAccess.ReadWrite); } } - using (updateFile) + try { long locatedCentralDirOffset = - updateFile.LocateBlockWithSignature(ZipConstants.EndOfCentralDirectorySignature, - baseLength, ZipConstants.EndOfCentralRecordBaseSize, 0xffff); + ZipFormat.LocateBlockWithSignature(updateFile, ZipConstants.EndOfCentralDirectorySignature, + baseLength, ZipConstants.EndOfCentralRecordBaseSize, 0xffff); if (locatedCentralDirOffset < 0) { throw new ZipException("Cannot find central directory"); @@ -2920,6 +2910,11 @@ private void UpdateCommentOnly() updateFile.Write(rawComment, 0, rawComment.Length); updateFile.SetLength(updateFile.Position); } + finally + { + if(updateFile != baseStream_) + updateFile.Dispose(); + } if (archiveStorage_.UpdateMode == FileUpdateMode.Safe) { @@ -3082,10 +3077,8 @@ private void RunUpdates() } byte[] theComment = (newComment_ != null) ? newComment_.RawComment : ZipStrings.ConvertToArray(comment_); - using (ZipHelperStream zhs = new ZipHelperStream(workFile.baseStream_)) - { - zhs.WriteEndOfCentralDirectory(updateCount_, sizeEntries, centralDirOffset, theComment); - } + ZipFormat.WriteEndOfCentralDirectory(workFile.baseStream_, updateCount_, + sizeEntries, centralDirOffset, theComment); endOfStream = workFile.baseStream_.Position; @@ -3426,13 +3419,8 @@ private ulong ReadLEUlong() #endregion Reading // NOTE this returns the offset of the first byte after the signature. - private long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) - { - using (ZipHelperStream les = new ZipHelperStream(baseStream_)) - { - return les.LocateBlockWithSignature(signature, endLocation, minimumBlockSize, maximumVariableData); - } - } + private long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) + => ZipFormat.LocateBlockWithSignature(baseStream_, signature, endLocation, minimumBlockSize, maximumVariableData); /// /// Search for and read the central directory of a zip file filling the entries array. diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs new file mode 100644 index 000000000..75f6b72d7 --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs @@ -0,0 +1,597 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Core; + +namespace ICSharpCode.SharpZipLib.Zip +{ + /// + /// Holds data pertinent to a data descriptor. + /// + public class DescriptorData + { + private long _crc; + + /// + /// Get /set the compressed size of data. + /// + public long CompressedSize { get; set; } + + /// + /// Get / set the uncompressed size of data + /// + public long Size { get; set; } + + /// + /// Get /set the crc value. + /// + public long Crc + { + get => _crc; + set => _crc = (value & 0xffffffff); + } + } + + internal struct EntryPatchData + { + public long SizePatchOffset { get; set; } + + public long CrcPatchOffset { get; set; } + } + + /// + /// This class assists with writing/reading from Zip files. + /// + internal static class ZipFormat + { + // Write the local file header + // TODO: ZipFormat.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage + internal static int WriteLocalHeader(Stream stream, ZipEntry entry, out EntryPatchData patchData, + bool headerInfoAvailable, bool patchEntryHeader, long streamOffset) + { + patchData = new EntryPatchData(); + + stream.WriteLEInt(ZipConstants.LocalHeaderSignature); + stream.WriteLEShort(entry.Version); + stream.WriteLEShort(entry.Flags); + stream.WriteLEShort((byte)entry.CompressionMethodForHeader); + stream.WriteLEInt((int)entry.DosTime); + + if (headerInfoAvailable) + { + stream.WriteLEInt((int)entry.Crc); + if (entry.LocalHeaderRequiresZip64) + { + stream.WriteLEInt(-1); + stream.WriteLEInt(-1); + } + else + { + stream.WriteLEInt((int)entry.CompressedSize + entry.EncryptionOverheadSize); + stream.WriteLEInt((int)entry.Size); + } + } + else + { + if (patchEntryHeader) + patchData.CrcPatchOffset = streamOffset + stream.Position; + + stream.WriteLEInt(0); // Crc + + if (patchEntryHeader) + patchData.SizePatchOffset = streamOffset + stream.Position; + + // For local header both sizes appear in Zip64 Extended Information + if (entry.LocalHeaderRequiresZip64 && patchEntryHeader) + { + stream.WriteLEInt(-1); + stream.WriteLEInt(-1); + } + else + { + stream.WriteLEInt(0); // Compressed size + stream.WriteLEInt(0); // Uncompressed size + } + } + + byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); + + if (name.Length > 0xFFFF) + { + throw new ZipException("Entry name too long."); + } + + var ed = new ZipExtraData(entry.ExtraData); + + if (entry.LocalHeaderRequiresZip64) + { + ed.StartNewEntry(); + if (headerInfoAvailable) + { + ed.AddLeLong(entry.Size); + ed.AddLeLong(entry.CompressedSize + entry.EncryptionOverheadSize); + } + else + { + ed.AddLeLong(-1); + ed.AddLeLong(-1); + } + ed.AddNewEntry(1); + + if (!ed.Find(1)) + { + throw new ZipException("Internal error cant find extra data"); + } + + patchData.SizePatchOffset = ed.CurrentReadIndex; + } + else + { + ed.Delete(1); + } + + if (entry.AESKeySize > 0) + { + AddExtraDataAES(entry, ed); + } + byte[] extra = ed.GetEntryData(); + + stream.WriteLEShort(name.Length); + stream.WriteLEShort(extra.Length); + + if (name.Length > 0) + { + stream.Write(name, 0, name.Length); + } + + if (entry.LocalHeaderRequiresZip64 && patchEntryHeader) + { + patchData.SizePatchOffset += streamOffset + stream.Position; + } + + if (extra.Length > 0) + { + stream.Write(extra, 0, extra.Length); + } + + return ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length; + } + + /// + /// Locates a block with the desired . + /// + /// + /// The signature to find. + /// Location, marking the end of block. + /// Minimum size of the block. + /// The maximum variable data. + /// Returns the offset of the first byte after the signature; -1 if not found + internal static long LocateBlockWithSignature(Stream stream, int signature, long endLocation, int minimumBlockSize, int maximumVariableData) + { + long pos = endLocation - minimumBlockSize; + if (pos < 0) + { + return -1; + } + + long giveUpMarker = Math.Max(pos - maximumVariableData, 0); + + // TODO: This loop could be optimized for speed. + do + { + if (pos < giveUpMarker) + { + return -1; + } + stream.Seek(pos--, SeekOrigin.Begin); + } while (stream.ReadLEInt() != signature); + + return stream.Position; + } + + /// + public static async Task WriteZip64EndOfCentralDirectoryAsync(Stream stream, long noOfEntries, + long sizeEntries, long centralDirOffset, CancellationToken cancellationToken) + { + await stream.WriteProcToStreamAsync(s => WriteZip64EndOfCentralDirectory(s, noOfEntries, sizeEntries, centralDirOffset), cancellationToken); + } + + /// + /// Write Zip64 end of central directory records (File header and locator). + /// + /// + /// The number of entries in the central directory. + /// The size of entries in the central directory. + /// The offset of the central directory. + internal static void WriteZip64EndOfCentralDirectory(Stream stream, long noOfEntries, long sizeEntries, long centralDirOffset) + { + long centralSignatureOffset = centralDirOffset + sizeEntries; + stream.WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature); + stream.WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12) + stream.WriteLEShort(ZipConstants.VersionMadeBy); // Version made by + stream.WriteLEShort(ZipConstants.VersionZip64); // Version to extract + stream.WriteLEInt(0); // Number of this disk + stream.WriteLEInt(0); // number of the disk with the start of the central directory + stream.WriteLELong(noOfEntries); // No of entries on this disk + stream.WriteLELong(noOfEntries); // Total No of entries in central directory + stream.WriteLELong(sizeEntries); // Size of the central directory + stream.WriteLELong(centralDirOffset); // offset of start of central directory + // zip64 extensible data sector not catered for here (variable size) + + // Write the Zip64 end of central directory locator + stream.WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature); + + // no of the disk with the start of the zip64 end of central directory + stream.WriteLEInt(0); + + // relative offset of the zip64 end of central directory record + stream.WriteLELong(centralSignatureOffset); + + // total number of disks + stream.WriteLEInt(1); + } + + /// + public static async Task WriteEndOfCentralDirectoryAsync(Stream stream, long noOfEntries, long sizeEntries, + long start, byte[] comment, CancellationToken cancellationToken) + => await stream.WriteProcToStreamAsync(s + => WriteEndOfCentralDirectory(s, noOfEntries, sizeEntries, start, comment), cancellationToken); + + /// + /// Write the required records to end the central directory. + /// + /// + /// The number of entries in the directory. + /// The size of the entries in the directory. + /// The start of the central directory. + /// The archive comment. (This can be null). + + internal static void WriteEndOfCentralDirectory(Stream stream, long noOfEntries, long sizeEntries, long start, byte[] comment) + { + if (noOfEntries >= 0xffff || + start >= 0xffffffff || + sizeEntries >= 0xffffffff) + { + WriteZip64EndOfCentralDirectory(stream, noOfEntries, sizeEntries, start); + } + + stream.WriteLEInt(ZipConstants.EndOfCentralDirectorySignature); + + // TODO: ZipFile Multi disk handling not done + stream.WriteLEShort(0); // number of this disk + stream.WriteLEShort(0); // no of disk with start of central dir + + // Number of entries + if (noOfEntries >= 0xffff) + { + stream.WriteLEUshort(0xffff); // Zip64 marker + stream.WriteLEUshort(0xffff); + } + else + { + stream.WriteLEShort((short)noOfEntries); // entries in central dir for this disk + stream.WriteLEShort((short)noOfEntries); // total entries in central directory + } + + // Size of the central directory + if (sizeEntries >= 0xffffffff) + { + stream.WriteLEUint(0xffffffff); // Zip64 marker + } + else + { + stream.WriteLEInt((int)sizeEntries); + } + + // offset of start of central directory + if (start >= 0xffffffff) + { + stream.WriteLEUint(0xffffffff); // Zip64 marker + } + else + { + stream.WriteLEInt((int)start); + } + + var commentLength = comment?.Length ?? 0; + + if (commentLength > 0xffff) + { + throw new ZipException($"Comment length ({commentLength}) is larger than 64K"); + } + + stream.WriteLEShort(commentLength); + + if (commentLength > 0) + { + stream.Write(comment, 0, commentLength); + } + } + + + + /// + /// Write a data descriptor. + /// + /// + /// The entry to write a descriptor for. + /// Returns the number of descriptor bytes written. + internal static int WriteDataDescriptor(Stream stream, ZipEntry entry) + { + if (entry == null) + { + throw new ArgumentNullException(nameof(entry)); + } + + int result = 0; + + // Add data descriptor if flagged as required + if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) + { + // The signature is not PKZIP originally but is now described as optional + // in the PKZIP Appnote documenting the format. + stream.WriteLEInt(ZipConstants.DataDescriptorSignature); + stream.WriteLEInt(unchecked((int)(entry.Crc))); + + result += 8; + + if (entry.LocalHeaderRequiresZip64) + { + stream.WriteLELong(entry.CompressedSize); + stream.WriteLELong(entry.Size); + result += 16; + } + else + { + stream.WriteLEInt((int)entry.CompressedSize); + stream.WriteLEInt((int)entry.Size); + result += 8; + } + } + + return result; + } + + /// + /// Read data descriptor at the end of compressed data. + /// + /// + /// if set to true [zip64]. + /// The data to fill in. + /// Returns the number of bytes read in the descriptor. + internal static void ReadDataDescriptor(Stream stream, bool zip64, DescriptorData data) + { + int intValue = stream.ReadLEInt(); + + // In theory this may not be a descriptor according to PKZIP appnote. + // In practice its always there. + if (intValue != ZipConstants.DataDescriptorSignature) + { + throw new ZipException("Data descriptor signature not found"); + } + + data.Crc = stream.ReadLEInt(); + + if (zip64) + { + data.CompressedSize = stream.ReadLELong(); + data.Size = stream.ReadLELong(); + } + else + { + data.CompressedSize = stream.ReadLEInt(); + data.Size = stream.ReadLEInt(); + } + } + + internal static int WriteEndEntry(Stream stream, ZipEntry entry) + { + stream.WriteLEInt(ZipConstants.CentralHeaderSignature); + stream.WriteLEShort((entry.HostSystem << 8) | entry.VersionMadeBy); + stream.WriteLEShort(entry.Version); + stream.WriteLEShort(entry.Flags); + stream.WriteLEShort((short)entry.CompressionMethodForHeader); + stream.WriteLEInt((int)entry.DosTime); + stream.WriteLEInt((int)entry.Crc); + + if (entry.IsZip64Forced() || + (entry.CompressedSize >= uint.MaxValue)) + { + stream.WriteLEInt(-1); + } + else + { + stream.WriteLEInt((int)entry.CompressedSize); + } + + if (entry.IsZip64Forced() || + (entry.Size >= uint.MaxValue)) + { + stream.WriteLEInt(-1); + } + else + { + stream.WriteLEInt((int)entry.Size); + } + + byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); + + if (name.Length > 0xffff) + { + throw new ZipException("Name too long."); + } + + var ed = new ZipExtraData(entry.ExtraData); + + if (entry.CentralHeaderRequiresZip64) + { + ed.StartNewEntry(); + if (entry.IsZip64Forced() || + (entry.Size >= 0xffffffff)) + { + ed.AddLeLong(entry.Size); + } + + if (entry.IsZip64Forced() || + (entry.CompressedSize >= 0xffffffff)) + { + ed.AddLeLong(entry.CompressedSize); + } + + if (entry.Offset >= 0xffffffff) + { + ed.AddLeLong(entry.Offset); + } + + ed.AddNewEntry(1); + } + else + { + ed.Delete(1); + } + + if (entry.AESKeySize > 0) + { + AddExtraDataAES(entry, ed); + } + byte[] extra = ed.GetEntryData(); + + byte[] entryComment = !(entry.Comment is null) + ? ZipStrings.ConvertToArray(entry.Flags, entry.Comment) + : Empty.Array(); + + if (entryComment.Length > 0xffff) + { + throw new ZipException("Comment too long."); + } + + stream.WriteLEShort(name.Length); + stream.WriteLEShort(extra.Length); + stream.WriteLEShort(entryComment.Length); + stream.WriteLEShort(0); // disk number + stream.WriteLEShort(0); // internal file attributes + // external file attributes + + if (entry.ExternalFileAttributes != -1) + { + stream.WriteLEInt(entry.ExternalFileAttributes); + } + else + { + if (entry.IsDirectory) + { // mark entry as directory (from nikolam.AT.perfectinfo.com) + stream.WriteLEInt(16); + } + else + { + stream.WriteLEInt(0); + } + } + + if (entry.Offset >= uint.MaxValue) + { + stream.WriteLEInt(-1); + } + else + { + stream.WriteLEInt((int)entry.Offset); + } + + if (name.Length > 0) + { + stream.Write(name, 0, name.Length); + } + + if (extra.Length > 0) + { + stream.Write(extra, 0, extra.Length); + } + + if (entryComment.Length > 0) + { + stream.Write(entryComment, 0, entryComment.Length); + } + + return ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length; + } + + internal static void AddExtraDataAES(ZipEntry entry, ZipExtraData extraData) + { + // Vendor Version: AE-1 IS 1. AE-2 is 2. With AE-2 no CRC is required and 0 is stored. + const int VENDOR_VERSION = 2; + // Vendor ID is the two ASCII characters "AE". + const int VENDOR_ID = 0x4541; //not 6965; + extraData.StartNewEntry(); + // Pack AES extra data field see http://www.winzip.com/aes_info.htm + //extraData.AddLeShort(7); // Data size (currently 7) + extraData.AddLeShort(VENDOR_VERSION); // 2 = AE-2 + extraData.AddLeShort(VENDOR_ID); // "AE" + extraData.AddData(entry.AESEncryptionStrength); // 1 = 128, 2 = 192, 3 = 256 + extraData.AddLeShort((int)entry.CompressionMethod); // The actual compression method used to compress the file + extraData.AddNewEntry(0x9901); + } + + internal static async Task PatchLocalHeaderAsync(Stream stream, ZipEntry entry, + EntryPatchData patchData, CancellationToken ct) + { + var initialPos = stream.Position; + + // Update CRC + stream.Seek(patchData.CrcPatchOffset, SeekOrigin.Begin); + await stream.WriteLEIntAsync((int)entry.Crc, ct); + + // Update Sizes + if (entry.LocalHeaderRequiresZip64) + { + if (patchData.SizePatchOffset == -1) + { + throw new ZipException("Entry requires zip64 but this has been turned off"); + } + // Seek to the Zip64 Extra Data + stream.Seek(patchData.SizePatchOffset, SeekOrigin.Begin); + + // Note: The order of the size fields is reversed when compared to the local header! + await stream.WriteLELongAsync(entry.Size, ct); + await stream.WriteLELongAsync(entry.CompressedSize, ct); + } + else + { + await stream.WriteLEIntAsync((int)entry.CompressedSize, ct); + await stream.WriteLEIntAsync((int)entry.Size, ct); + } + + stream.Seek(initialPos, SeekOrigin.Begin); + } + + internal static void PatchLocalHeaderSync(Stream stream, ZipEntry entry, + EntryPatchData patchData) + { + var initialPos = stream.Position; + stream.Seek(patchData.CrcPatchOffset, SeekOrigin.Begin); + stream.WriteLEInt((int)entry.Crc); + + if (entry.LocalHeaderRequiresZip64) + { + if (patchData.SizePatchOffset == -1) + { + throw new ZipException("Entry requires zip64 but this has been turned off"); + } + + // Seek to the Zip64 Extra Data + stream.Seek(patchData.SizePatchOffset, SeekOrigin.Begin); + + // Note: The order of the size fields is reversed when compared to the local header! + stream.WriteLELong(entry.Size); + stream.WriteLELong(entry.CompressedSize); + } + else + { + stream.WriteLEInt((int)entry.CompressedSize); + stream.WriteLEInt((int)entry.Size); + } + + stream.Seek(initialPos, SeekOrigin.Begin); + } + } +} diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs index da65630c6..e69de29bb 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipHelperStream.cs @@ -1,629 +0,0 @@ -using System; -using System.IO; - -namespace ICSharpCode.SharpZipLib.Zip -{ - /// - /// Holds data pertinent to a data descriptor. - /// - public class DescriptorData - { - /// - /// Get /set the compressed size of data. - /// - public long CompressedSize - { - get { return compressedSize; } - set { compressedSize = value; } - } - - /// - /// Get / set the uncompressed size of data - /// - public long Size - { - get { return size; } - set { size = value; } - } - - /// - /// Get /set the crc value. - /// - public long Crc - { - get { return crc; } - set { crc = (value & 0xffffffff); } - } - - #region Instance Fields - - private long size; - private long compressedSize; - private long crc; - - #endregion Instance Fields - } - - internal class EntryPatchData - { - public long SizePatchOffset - { - get { return sizePatchOffset_; } - set { sizePatchOffset_ = value; } - } - - public long CrcPatchOffset - { - get { return crcPatchOffset_; } - set { crcPatchOffset_ = value; } - } - - #region Instance Fields - - private long sizePatchOffset_; - private long crcPatchOffset_; - - #endregion Instance Fields - } - - /// - /// This class assists with writing/reading from Zip files. - /// - internal class ZipHelperStream : Stream - { - #region Constructors - - /// - /// Initialise an instance of this class. - /// - /// The name of the file to open. - public ZipHelperStream(string name) - { - stream_ = new FileStream(name, FileMode.Open, FileAccess.ReadWrite); - isOwner_ = true; - } - - /// - /// Initialise a new instance of . - /// - /// The stream to use. - public ZipHelperStream(Stream stream) - { - stream_ = stream; - } - - #endregion Constructors - - /// - /// Get / set a value indicating whether the underlying stream is owned or not. - /// - /// If the stream is owned it is closed when this instance is closed. - public bool IsStreamOwner - { - get { return isOwner_; } - set { isOwner_ = value; } - } - - #region Base Stream Methods - - public override bool CanRead - { - get { return stream_.CanRead; } - } - - public override bool CanSeek - { - get { return stream_.CanSeek; } - } - - public override bool CanTimeout - { - get { return stream_.CanTimeout; } - } - - public override long Length - { - get { return stream_.Length; } - } - - public override long Position - { - get { return stream_.Position; } - set { stream_.Position = value; } - } - - public override bool CanWrite - { - get { return stream_.CanWrite; } - } - - public override void Flush() - { - stream_.Flush(); - } - - public override long Seek(long offset, SeekOrigin origin) - { - return stream_.Seek(offset, origin); - } - - public override void SetLength(long value) - { - stream_.SetLength(value); - } - - public override int Read(byte[] buffer, int offset, int count) - { - return stream_.Read(buffer, offset, count); - } - - public override void Write(byte[] buffer, int offset, int count) - { - stream_.Write(buffer, offset, count); - } - - /// - /// Close the stream. - /// - /// - /// The underlying stream is closed only if is true. - /// - protected override void Dispose(bool disposing) - { - Stream toClose = stream_; - stream_ = null; - if (isOwner_ && (toClose != null)) - { - isOwner_ = false; - toClose.Dispose(); - } - } - - #endregion Base Stream Methods - - // Write the local file header - // TODO: ZipHelperStream.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage - private void WriteLocalHeader(ZipEntry entry, EntryPatchData patchData) - { - CompressionMethod method = entry.CompressionMethod; - bool headerInfoAvailable = true; // How to get this? - bool patchEntryHeader = false; - - WriteLEInt(ZipConstants.LocalHeaderSignature); - - WriteLEShort(entry.Version); - WriteLEShort(entry.Flags); - WriteLEShort((byte)method); - WriteLEInt((int)entry.DosTime); - - if (headerInfoAvailable == true) - { - WriteLEInt((int)entry.Crc); - if (entry.LocalHeaderRequiresZip64) - { - WriteLEInt(-1); - WriteLEInt(-1); - } - else - { - WriteLEInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); - WriteLEInt((int)entry.Size); - } - } - else - { - if (patchData != null) - { - patchData.CrcPatchOffset = stream_.Position; - } - WriteLEInt(0); // Crc - - if (patchData != null) - { - patchData.SizePatchOffset = stream_.Position; - } - - // For local header both sizes appear in Zip64 Extended Information - if (entry.LocalHeaderRequiresZip64 && patchEntryHeader) - { - WriteLEInt(-1); - WriteLEInt(-1); - } - else - { - WriteLEInt(0); // Compressed size - WriteLEInt(0); // Uncompressed size - } - } - - byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); - - if (name.Length > 0xFFFF) - { - throw new ZipException("Entry name too long."); - } - - var ed = new ZipExtraData(entry.ExtraData); - - if (entry.LocalHeaderRequiresZip64 && (headerInfoAvailable || patchEntryHeader)) - { - ed.StartNewEntry(); - if (headerInfoAvailable) - { - ed.AddLeLong(entry.Size); - ed.AddLeLong(entry.CompressedSize); - } - else - { - ed.AddLeLong(-1); - ed.AddLeLong(-1); - } - ed.AddNewEntry(1); - - if (!ed.Find(1)) - { - throw new ZipException("Internal error cant find extra data"); - } - - if (patchData != null) - { - patchData.SizePatchOffset = ed.CurrentReadIndex; - } - } - else - { - ed.Delete(1); - } - - byte[] extra = ed.GetEntryData(); - - WriteLEShort(name.Length); - WriteLEShort(extra.Length); - - if (name.Length > 0) - { - stream_.Write(name, 0, name.Length); - } - - if (entry.LocalHeaderRequiresZip64 && patchEntryHeader) - { - patchData.SizePatchOffset += stream_.Position; - } - - if (extra.Length > 0) - { - stream_.Write(extra, 0, extra.Length); - } - } - - /// - /// Locates a block with the desired . - /// - /// The signature to find. - /// Location, marking the end of block. - /// Minimum size of the block. - /// The maximum variable data. - /// Returns the offset of the first byte after the signature; -1 if not found - public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) - { - long pos = endLocation - minimumBlockSize; - if (pos < 0) - { - return -1; - } - - long giveUpMarker = Math.Max(pos - maximumVariableData, 0); - - // TODO: This loop could be optimised for speed. - do - { - if (pos < giveUpMarker) - { - return -1; - } - Seek(pos--, SeekOrigin.Begin); - } while (ReadLEInt() != signature); - - return Position; - } - - /// - /// Write Zip64 end of central directory records (File header and locator). - /// - /// The number of entries in the central directory. - /// The size of entries in the central directory. - /// The offset of the central directory. - public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset) - { - long centralSignatureOffset = centralDirOffset + sizeEntries; - WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature); - WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12) - WriteLEShort(ZipConstants.VersionMadeBy); // Version made by - WriteLEShort(ZipConstants.VersionZip64); // Version to extract - WriteLEInt(0); // Number of this disk - WriteLEInt(0); // number of the disk with the start of the central directory - WriteLELong(noOfEntries); // No of entries on this disk - WriteLELong(noOfEntries); // Total No of entries in central directory - WriteLELong(sizeEntries); // Size of the central directory - WriteLELong(centralDirOffset); // offset of start of central directory - // zip64 extensible data sector not catered for here (variable size) - - // Write the Zip64 end of central directory locator - WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature); - - // no of the disk with the start of the zip64 end of central directory - WriteLEInt(0); - - // relative offset of the zip64 end of central directory record - WriteLELong(centralSignatureOffset); - - // total number of disks - WriteLEInt(1); - } - - /// - /// Write the required records to end the central directory. - /// - /// The number of entries in the directory. - /// The size of the entries in the directory. - /// The start of the central directory. - /// The archive comment. (This can be null). - public void WriteEndOfCentralDirectory(long noOfEntries, long sizeEntries, - long startOfCentralDirectory, byte[] comment) - { - if ((noOfEntries >= 0xffff) || - (startOfCentralDirectory >= 0xffffffff) || - (sizeEntries >= 0xffffffff)) - { - WriteZip64EndOfCentralDirectory(noOfEntries, sizeEntries, startOfCentralDirectory); - } - - WriteLEInt(ZipConstants.EndOfCentralDirectorySignature); - - // TODO: ZipFile Multi disk handling not done - WriteLEShort(0); // number of this disk - WriteLEShort(0); // no of disk with start of central dir - - // Number of entries - if (noOfEntries >= 0xffff) - { - WriteLEUshort(0xffff); // Zip64 marker - WriteLEUshort(0xffff); - } - else - { - WriteLEShort((short)noOfEntries); // entries in central dir for this disk - WriteLEShort((short)noOfEntries); // total entries in central directory - } - - // Size of the central directory - if (sizeEntries >= 0xffffffff) - { - WriteLEUint(0xffffffff); // Zip64 marker - } - else - { - WriteLEInt((int)sizeEntries); - } - - // offset of start of central directory - if (startOfCentralDirectory >= 0xffffffff) - { - WriteLEUint(0xffffffff); // Zip64 marker - } - else - { - WriteLEInt((int)startOfCentralDirectory); - } - - int commentLength = (comment != null) ? comment.Length : 0; - - if (commentLength > 0xffff) - { - throw new ZipException(string.Format("Comment length({0}) is too long can only be 64K", commentLength)); - } - - WriteLEShort(commentLength); - - if (commentLength > 0) - { - Write(comment, 0, comment.Length); - } - } - - #region LE value reading/writing - - /// - /// Read an unsigned short in little endian byte order. - /// - /// Returns the value read. - /// - /// An i/o error occurs. - /// - /// - /// The file ends prematurely - /// - public int ReadLEShort() - { - int byteValue1 = stream_.ReadByte(); - - if (byteValue1 < 0) - { - throw new EndOfStreamException(); - } - - int byteValue2 = stream_.ReadByte(); - if (byteValue2 < 0) - { - throw new EndOfStreamException(); - } - - return byteValue1 | (byteValue2 << 8); - } - - /// - /// Read an int in little endian byte order. - /// - /// Returns the value read. - /// - /// An i/o error occurs. - /// - /// - /// The file ends prematurely - /// - public int ReadLEInt() - { - return ReadLEShort() | (ReadLEShort() << 16); - } - - /// - /// Read a long in little endian byte order. - /// - /// The value read. - public long ReadLELong() - { - return (uint)ReadLEInt() | ((long)ReadLEInt() << 32); - } - - /// - /// Write an unsigned short in little endian byte order. - /// - /// The value to write. - public void WriteLEShort(int value) - { - stream_.WriteByte((byte)(value & 0xff)); - stream_.WriteByte((byte)((value >> 8) & 0xff)); - } - - /// - /// Write a ushort in little endian byte order. - /// - /// The value to write. - public void WriteLEUshort(ushort value) - { - stream_.WriteByte((byte)(value & 0xff)); - stream_.WriteByte((byte)(value >> 8)); - } - - /// - /// Write an int in little endian byte order. - /// - /// The value to write. - public void WriteLEInt(int value) - { - WriteLEShort(value); - WriteLEShort(value >> 16); - } - - /// - /// Write a uint in little endian byte order. - /// - /// The value to write. - public void WriteLEUint(uint value) - { - WriteLEUshort((ushort)(value & 0xffff)); - WriteLEUshort((ushort)(value >> 16)); - } - - /// - /// Write a long in little endian byte order. - /// - /// The value to write. - public void WriteLELong(long value) - { - WriteLEInt((int)value); - WriteLEInt((int)(value >> 32)); - } - - /// - /// Write a ulong in little endian byte order. - /// - /// The value to write. - public void WriteLEUlong(ulong value) - { - WriteLEUint((uint)(value & 0xffffffff)); - WriteLEUint((uint)(value >> 32)); - } - - #endregion LE value reading/writing - - /// - /// Write a data descriptor. - /// - /// The entry to write a descriptor for. - /// Returns the number of descriptor bytes written. - public int WriteDataDescriptor(ZipEntry entry) - { - if (entry == null) - { - throw new ArgumentNullException(nameof(entry)); - } - - int result = 0; - - // Add data descriptor if flagged as required - if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) - { - // The signature is not PKZIP originally but is now described as optional - // in the PKZIP Appnote documenting the format. - WriteLEInt(ZipConstants.DataDescriptorSignature); - WriteLEInt(unchecked((int)(entry.Crc))); - - result += 8; - - if (entry.LocalHeaderRequiresZip64) - { - WriteLELong(entry.CompressedSize); - WriteLELong(entry.Size); - result += 16; - } - else - { - WriteLEInt((int)entry.CompressedSize); - WriteLEInt((int)entry.Size); - result += 8; - } - } - - return result; - } - - /// - /// Read data descriptor at the end of compressed data. - /// - /// if set to true [zip64]. - /// The data to fill in. - /// Returns the number of bytes read in the descriptor. - public void ReadDataDescriptor(bool zip64, DescriptorData data) - { - int intValue = ReadLEInt(); - - // In theory this may not be a descriptor according to PKZIP appnote. - // In practice its always there. - if (intValue != ZipConstants.DataDescriptorSignature) - { - throw new ZipException("Data descriptor signature not found"); - } - - data.Crc = ReadLEInt(); - - if (zip64) - { - data.CompressedSize = ReadLELong(); - data.Size = ReadLELong(); - } - else - { - data.CompressedSize = ReadLEInt(); - data.Size = ReadLEInt(); - } - } - - #region Instance Fields - - private bool isOwner_; - private Stream stream_; - - #endregion Instance Fields - } -} diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 79d65f560..7aa3295fe 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -7,6 +7,8 @@ using System.Collections.Generic; using System.IO; using System.Security.Cryptography; +using System.Threading; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Zip { @@ -154,7 +156,7 @@ public UseZip64 UseZip64 /// Defaults to , set to null to disable transforms and use names as supplied. /// public INameTransform NameTransform { get; set; } = new PathTransformer(); - + /// /// Get/set the password used for encryption. /// @@ -217,17 +219,10 @@ private void WriteLeLong(long value) // Apply any configured transforms/cleaning to the name of the supplied entry. private void TransformEntryName(ZipEntry entry) { - if (this.NameTransform != null) - { - if (entry.IsDirectory) - { - entry.Name = this.NameTransform.TransformDirectory(entry.Name); - } - else - { - entry.Name = this.NameTransform.TransformFile(entry.Name); - } - } + if (NameTransform == null) return; + entry.Name = entry.IsDirectory + ? NameTransform.TransformDirectory(entry.Name) + : NameTransform.TransformFile(entry.Name); } /// @@ -244,7 +239,7 @@ private void TransformEntryName(ZipEntry entry) /// if entry passed is null. /// /// - /// if an I/O error occured. + /// if an I/O error occurred. /// /// /// if stream was finished @@ -258,6 +253,32 @@ private void TransformEntryName(ZipEntry entry) /// The Compression method specified for the entry is unsupported. /// public void PutNextEntry(ZipEntry entry) + { + if (curEntry != null) + { + CloseEntry(); + } + + PutNextEntry(baseOutputStream_, entry); + + if (entry.IsCrypted) + { + WriteOutput(GetEntryEncryptionHeader(entry)); + } + } + + private void WriteOutput(byte[] bytes) + => baseOutputStream_.Write(bytes, 0, bytes.Length); + + private Task WriteOutputAsync(byte[] bytes) + => baseOutputStream_.WriteAsync(bytes, 0, bytes.Length); + + private byte[] GetEntryEncryptionHeader(ZipEntry entry) => + entry.AESKeySize > 0 + ? InitializeAESPassword(entry, Password) + : CreateZipCryptoHeader(entry.Crc < 0 ? entry.DosTime << 16 : entry.Crc); + + internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0) { if (entry == null) { @@ -269,11 +290,6 @@ public void PutNextEntry(ZipEntry entry) throw new InvalidOperationException("ZipOutputStream was finished"); } - if (curEntry != null) - { - CloseEntry(); - } - if (entries.Count == int.MaxValue) { throw new ZipException("Too many entries for Zip file"); @@ -365,128 +381,21 @@ public void PutNextEntry(ZipEntry entry) entry.CompressionMethod = (CompressionMethod)method; curMethod = method; - sizePatchPos = -1; if ((useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic))) { entry.ForceZip64(); } - // Write the local file header - WriteLeInt(ZipConstants.LocalHeaderSignature); - - WriteLeShort(entry.Version); - WriteLeShort(entry.Flags); - WriteLeShort((byte)entry.CompressionMethodForHeader); - WriteLeInt((int)entry.DosTime); - - // TODO: Refactor header writing. Its done in several places. - if (headerInfoAvailable) - { - WriteLeInt((int)entry.Crc); - if (entry.LocalHeaderRequiresZip64) - { - WriteLeInt(-1); - WriteLeInt(-1); - } - else - { - WriteLeInt((int)entry.CompressedSize + entry.EncryptionOverheadSize); - WriteLeInt((int)entry.Size); - } - } - else - { - if (patchEntryHeader) - { - crcPatchPos = baseOutputStream_.Position; - } - WriteLeInt(0); // Crc - - if (patchEntryHeader) - { - sizePatchPos = baseOutputStream_.Position; - } - - // For local header both sizes appear in Zip64 Extended Information - if (entry.LocalHeaderRequiresZip64 || patchEntryHeader) - { - WriteLeInt(-1); - WriteLeInt(-1); - } - else - { - WriteLeInt(0); // Compressed size - WriteLeInt(0); // Uncompressed size - } - } - - // Apply any required transforms to the entry name, and then convert to byte array format. + // Apply any required transforms to the entry name TransformEntryName(entry); - byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); - if (name.Length > 0xFFFF) - { - throw new ZipException("Entry name too long."); - } - - var ed = new ZipExtraData(entry.ExtraData); - - if (entry.LocalHeaderRequiresZip64) - { - ed.StartNewEntry(); - if (headerInfoAvailable) - { - ed.AddLeLong(entry.Size); - ed.AddLeLong(entry.CompressedSize + entry.EncryptionOverheadSize); - } - else - { - ed.AddLeLong(-1); - ed.AddLeLong(-1); - } - ed.AddNewEntry(1); - - if (!ed.Find(1)) - { - throw new ZipException("Internal error cant find extra data"); - } - - if (patchEntryHeader) - { - sizePatchPos = ed.CurrentReadIndex; - } - } - else - { - ed.Delete(1); - } - - if (entry.AESKeySize > 0) - { - AddExtraDataAES(entry, ed); - } - byte[] extra = ed.GetEntryData(); - - WriteLeShort(name.Length); - WriteLeShort(extra.Length); - - if (name.Length > 0) - { - baseOutputStream_.Write(name, 0, name.Length); - } - - if (entry.LocalHeaderRequiresZip64 && patchEntryHeader) - { - sizePatchPos += baseOutputStream_.Position; - } + // Write the local file header + offset += ZipFormat.WriteLocalHeader(stream, entry, out var entryPatchData, + headerInfoAvailable, patchEntryHeader, streamOffset); - if (extra.Length > 0) - { - baseOutputStream_.Write(extra, 0, extra.Length); - } + patchData = entryPatchData; - offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length; // Fix offsetOfCentraldir for AES if (entry.AESKeySize > 0) offset += entry.AESOverheadSize; @@ -500,25 +409,47 @@ public void PutNextEntry(ZipEntry entry) deflater_.SetLevel(compressionLevel); } size = 0; + + } - if (entry.IsCrypted) - { - if (entry.AESKeySize > 0) - { - WriteAESHeader(entry); - } - else - { - if (entry.Crc < 0) - { // so testing Zip will says its ok - WriteEncryptionHeader(entry.DosTime << 16); - } - else - { - WriteEncryptionHeader(entry.Crc); - } - } - } + /// + /// Starts a new Zip entry. It automatically closes the previous + /// entry if present. + /// All entry elements bar name are optional, but must be correct if present. + /// If the compression method is stored and the output is not patchable + /// the compression for that entry is automatically changed to deflate level 0 + /// + /// + /// the entry. + /// + /// The that can be used to cancel the operation. + /// + /// if entry passed is null. + /// + /// + /// if an I/O error occured. + /// + /// + /// if stream was finished + /// + /// + /// Too many entries in the Zip file
+ /// Entry name is too long
+ /// Finish has already been called
+ ///
+ /// + /// The Compression method specified for the entry is unsupported. + /// + public async Task PutNextEntryAsync(ZipEntry entry, CancellationToken ct = default) + { + if (curEntry != null) await CloseEntryAsync(ct); + await baseOutputStream_.WriteProcToStreamAsync(s => + { + PutNextEntry(s, entry, baseOutputStream_.Position); + }, ct); + + if (!entry.IsCrypted) return; + await WriteOutputAsync(GetEntryEncryptionHeader(entry)); } /// @@ -534,6 +465,37 @@ public void PutNextEntry(ZipEntry entry) /// No entry is active. /// public void CloseEntry() + { + WriteEntryFooter(baseOutputStream_); + + // Patch the header if possible + if (patchEntryHeader) + { + patchEntryHeader = false; + ZipFormat.PatchLocalHeaderSync(baseOutputStream_, curEntry, patchData); + } + + entries.Add(curEntry); + curEntry = null; + } + + /// + public async Task CloseEntryAsync(CancellationToken ct) + { + await baseOutputStream_.WriteProcToStreamAsync(WriteEntryFooter, ct); + + // Patch the header if possible + if (patchEntryHeader) + { + patchEntryHeader = false; + await ZipFormat.PatchLocalHeaderAsync(baseOutputStream_, curEntry, patchData, ct); + } + + entries.Add(curEntry); + curEntry = null; + } + + internal void WriteEntryFooter(Stream stream) { if (curEntry == null) { @@ -565,7 +527,7 @@ public void CloseEntry() // Write the AES Authentication Code (a hash of the compressed and encrypted data) if (curEntry.AESKeySize > 0) { - baseOutputStream_.Write(AESAuthCode, 0, 10); + stream.Write(AESAuthCode, 0, 10); // Always use 0 as CRC for AE-2 format curEntry.Crc = 0; } @@ -606,91 +568,69 @@ public void CloseEntry() curEntry.CompressedSize += curEntry.EncryptionOverheadSize; } - // Patch the header if possible - if (patchEntryHeader) - { - patchEntryHeader = false; - - long curPos = baseOutputStream_.Position; - baseOutputStream_.Seek(crcPatchPos, SeekOrigin.Begin); - WriteLeInt((int)curEntry.Crc); - - if (curEntry.LocalHeaderRequiresZip64) - { - if (sizePatchPos == -1) - { - throw new ZipException("Entry requires zip64 but this has been turned off"); - } - - baseOutputStream_.Seek(sizePatchPos, SeekOrigin.Begin); - WriteLeLong(curEntry.Size); - WriteLeLong(curEntry.CompressedSize); - } - else - { - WriteLeInt((int)curEntry.CompressedSize); - WriteLeInt((int)curEntry.Size); - } - baseOutputStream_.Seek(curPos, SeekOrigin.Begin); - } - // Add data descriptor if flagged as required if ((curEntry.Flags & 8) != 0) { - WriteLeInt(ZipConstants.DataDescriptorSignature); - WriteLeInt(unchecked((int)curEntry.Crc)); + stream.WriteLEInt(ZipConstants.DataDescriptorSignature); + stream.WriteLEInt(unchecked((int)curEntry.Crc)); if (curEntry.LocalHeaderRequiresZip64) { - WriteLeLong(curEntry.CompressedSize); - WriteLeLong(curEntry.Size); + stream.WriteLELong(curEntry.CompressedSize); + stream.WriteLELong(curEntry.Size); offset += ZipConstants.Zip64DataDescriptorSize; } else { - WriteLeInt((int)curEntry.CompressedSize); - WriteLeInt((int)curEntry.Size); + stream.WriteLEInt((int)curEntry.CompressedSize); + stream.WriteLEInt((int)curEntry.Size); offset += ZipConstants.DataDescriptorSize; } } - - entries.Add(curEntry); - curEntry = null; } - /// - /// Initializes encryption keys based on given . - /// - /// The password. - private void InitializePassword(string password) - { - var pkManaged = new PkzipClassicManaged(); - byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password)); - cryptoTransform_ = pkManaged.CreateEncryptor(key, null); - } + + // File format for AES: + // Size (bytes) Content + // ------------ ------- + // Variable Salt value + // 2 Password verification value + // Variable Encrypted file data + // 10 Authentication code + // + // Value in the "compressed size" fields of the local file header and the central directory entry + // is the total size of all the items listed above. In other words, it is the total size of the + // salt value, password verification value, encrypted data, and authentication code. + /// /// Initializes encryption keys based on given password. /// - private void InitializeAESPassword(ZipEntry entry, string rawPassword, - out byte[] salt, out byte[] pwdVerifier) + protected byte[] InitializeAESPassword(ZipEntry entry, string rawPassword) { - salt = new byte[entry.AESSaltLen]; - + var salt = new byte[entry.AESSaltLen]; // Salt needs to be cryptographically random, and unique per file + if (_aesRnd == null) + _aesRnd = RandomNumberGenerator.Create(); _aesRnd.GetBytes(salt); - int blockSize = entry.AESKeySize / 8; // bits to bytes cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); - pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; - } - private void WriteEncryptionHeader(long crcValue) + var headBytes = new byte[salt.Length + 2]; + + Array.Copy(salt, headBytes, salt.Length); + Array.Copy(((ZipAESTransform)cryptoTransform_).PwdVerifier, 0, + headBytes, headBytes.Length - 2, 2); + + return headBytes; + } + + private byte[] CreateZipCryptoHeader(long crcValue) { offset += ZipConstants.CryptoHeaderSize; - InitializePassword(Password); + InitializeZipCryptoPassword(Password); byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; using (var rng = new RNGCryptoServiceProvider()) @@ -701,47 +641,21 @@ private void WriteEncryptionHeader(long crcValue) cryptBuffer[11] = (byte)(crcValue >> 24); EncryptBlock(cryptBuffer, 0, cryptBuffer.Length); - baseOutputStream_.Write(cryptBuffer, 0, cryptBuffer.Length); - } - private static void AddExtraDataAES(ZipEntry entry, ZipExtraData extraData) - { - // Vendor Version: AE-1 IS 1. AE-2 is 2. With AE-2 no CRC is required and 0 is stored. - const int VENDOR_VERSION = 2; - // Vendor ID is the two ASCII characters "AE". - const int VENDOR_ID = 0x4541; //not 6965; - extraData.StartNewEntry(); - // Pack AES extra data field see http://www.winzip.com/aes_info.htm - //extraData.AddLeShort(7); // Data size (currently 7) - extraData.AddLeShort(VENDOR_VERSION); // 2 = AE-2 - extraData.AddLeShort(VENDOR_ID); // "AE" - extraData.AddData(entry.AESEncryptionStrength); // 1 = 128, 2 = 192, 3 = 256 - extraData.AddLeShort((int)entry.CompressionMethod); // The actual compression method used to compress the file - extraData.AddNewEntry(0x9901); + return cryptBuffer; } - - // Replaces WriteEncryptionHeader for AES - // - private void WriteAESHeader(ZipEntry entry) + + /// + /// Initializes encryption keys based on given . + /// + /// The password. + private void InitializeZipCryptoPassword(string password) { - byte[] salt; - byte[] pwdVerifier; - InitializeAESPassword(entry, Password, out salt, out pwdVerifier); - // File format for AES: - // Size (bytes) Content - // ------------ ------- - // Variable Salt value - // 2 Password verification value - // Variable Encrypted file data - // 10 Authentication code - // - // Value in the "compressed size" fields of the local file header and the central directory entry - // is the total size of all the items listed above. In other words, it is the total size of the - // salt value, password verification value, encrypted data, and authentication code. - baseOutputStream_.Write(salt, 0, salt.Length); - baseOutputStream_.Write(pwdVerifier, 0, pwdVerifier.Length); + var pkManaged = new PkzipClassicManaged(); + byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password)); + cryptoTransform_ = pkManaged.CreateEncryptor(key, null); } - + /// /// Writes the given buffer to the current entry. /// @@ -849,144 +763,48 @@ public override void Finish() long numEntries = entries.Count; long sizeEntries = 0; - foreach (ZipEntry entry in entries) + foreach (var entry in entries) { - WriteLeInt(ZipConstants.CentralHeaderSignature); - WriteLeShort((entry.HostSystem << 8) | entry.VersionMadeBy); - WriteLeShort(entry.Version); - WriteLeShort(entry.Flags); - WriteLeShort((short)entry.CompressionMethodForHeader); - WriteLeInt((int)entry.DosTime); - WriteLeInt((int)entry.Crc); - - if (entry.IsZip64Forced() || - (entry.CompressedSize >= uint.MaxValue)) - { - WriteLeInt(-1); - } - else - { - WriteLeInt((int)entry.CompressedSize); - } - - if (entry.IsZip64Forced() || - (entry.Size >= uint.MaxValue)) - { - WriteLeInt(-1); - } - else - { - WriteLeInt((int)entry.Size); - } - - byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); - - if (name.Length > 0xffff) - { - throw new ZipException("Name too long."); - } - - var ed = new ZipExtraData(entry.ExtraData); - - if (entry.CentralHeaderRequiresZip64) - { - ed.StartNewEntry(); - if (entry.IsZip64Forced() || - (entry.Size >= 0xffffffff)) - { - ed.AddLeLong(entry.Size); - } - - if (entry.IsZip64Forced() || - (entry.CompressedSize >= 0xffffffff)) - { - ed.AddLeLong(entry.CompressedSize); - } + sizeEntries += ZipFormat.WriteEndEntry(baseOutputStream_, entry); + } - if (entry.Offset >= 0xffffffff) - { - ed.AddLeLong(entry.Offset); - } + ZipFormat.WriteEndOfCentralDirectory(baseOutputStream_, numEntries, sizeEntries, offset, zipComment); - ed.AddNewEntry(1); - } - else - { - ed.Delete(1); - } + entries = null; + } - if (entry.AESKeySize > 0) + /// > + public override async Task FinishAsync(CancellationToken ct) + { + using (var ms = new MemoryStream()) + { + if (entries == null) { - AddExtraDataAES(entry, ed); + return; } - byte[] extra = ed.GetEntryData(); - - byte[] entryComment = - (entry.Comment != null) ? - ZipStrings.ConvertToArray(entry.Flags, entry.Comment) : - Empty.Array(); - if (entryComment.Length > 0xffff) + if (curEntry != null) { - throw new ZipException("Comment too long."); + await CloseEntryAsync(ct); } - WriteLeShort(name.Length); - WriteLeShort(extra.Length); - WriteLeShort(entryComment.Length); - WriteLeShort(0); // disk number - WriteLeShort(0); // internal file attributes - // external file attributes + long numEntries = entries.Count; + long sizeEntries = 0; - if (entry.ExternalFileAttributes != -1) + foreach (var entry in entries) { - WriteLeInt(entry.ExternalFileAttributes); - } - else - { - if (entry.IsDirectory) - { // mark entry as directory (from nikolam.AT.perfectinfo.com) - WriteLeInt(16); - } - else + await baseOutputStream_.WriteProcToStreamAsync(ms, s => { - WriteLeInt(0); - } - } - - if (entry.Offset >= uint.MaxValue) - { - WriteLeInt(-1); - } - else - { - WriteLeInt((int)entry.Offset); + sizeEntries += ZipFormat.WriteEndEntry(s, entry); + }, ct); } - if (name.Length > 0) - { - baseOutputStream_.Write(name, 0, name.Length); - } - - if (extra.Length > 0) - { - baseOutputStream_.Write(extra, 0, extra.Length); - } - - if (entryComment.Length > 0) - { - baseOutputStream_.Write(entryComment, 0, entryComment.Length); - } + await baseOutputStream_.WriteProcToStreamAsync(ms, s + => ZipFormat.WriteEndOfCentralDirectory(s, numEntries, sizeEntries, offset, zipComment), + ct); - sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length; + entries = null; } - - using (ZipHelperStream zhs = new ZipHelperStream(baseOutputStream_)) - { - zhs.WriteEndOfCentralDirectory(numEntries, sizeEntries, offset, zipComment); - } - - entries = null; } /// @@ -1047,14 +865,9 @@ public override void Flush() private bool patchEntryHeader; /// - /// Position to patch crc - /// - private long crcPatchPos = -1; - - /// - /// Position to patch size. + /// The values to patch in the entry local header /// - private long sizePatchPos = -1; + private EntryPatchData patchData; // Default is dynamic which is not backwards compatible and can cause problems // with XP's built in compression which cant read Zip64 archives. diff --git a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs index 9df9319b4..e9ba0ad77 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Base/InflaterDeflaterTests.cs @@ -6,6 +6,7 @@ using System.IO; using System.Security; using System.Text; +using System.Threading; using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.Base @@ -113,7 +114,7 @@ private async Task DeflateAsync(byte[] data, int level, bool zlib) outStream.IsStreamOwner = false; await outStream.WriteAsync(data, 0, data.Length); await outStream.FlushAsync(); - outStream.Finish(); + await outStream.FinishAsync(CancellationToken.None); } return memoryStream; } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Core/ByteOrderUtilsTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Core/ByteOrderUtilsTests.cs new file mode 100644 index 000000000..1a5d271ff --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/Core/ByteOrderUtilsTests.cs @@ -0,0 +1,137 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using NUnit.Framework; +using BO = ICSharpCode.SharpZipLib.Core.ByteOrderStreamExtensions; +using ICSharpCode.SharpZipLib.Core; + +// ReSharper disable InconsistentNaming + +namespace ICSharpCode.SharpZipLib.Tests.Core +{ + [TestFixture] + [Category("Core")] + public class ByteOrderUtilsTests + { + private const short native16 = 0x1234; + private static readonly byte[] swapped16 = { 0x34, 0x12 }; + + private const int native32 = 0x12345678; + private static readonly byte[] swapped32 = { 0x78, 0x56, 0x34, 0x12 }; + + private const long native64 = 0x123456789abcdef0; + private static readonly byte[] swapped64 = { 0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12 }; + + [Test] + public void ToSwappedBytes() + { + Assert.AreEqual(swapped16, BO.SwappedBytes(native16)); + Assert.AreEqual(swapped16, BO.SwappedBytes((ushort)native16)); + + Assert.AreEqual(swapped32, BO.SwappedBytes(native32)); + Assert.AreEqual(swapped32, BO.SwappedBytes((uint)native32)); + + Assert.AreEqual(swapped64, BO.SwappedBytes(native64)); + Assert.AreEqual(swapped64, BO.SwappedBytes((ulong)native64)); + } + + [Test] + public void FromSwappedBytes() + { + Assert.AreEqual(native16, BO.SwappedS16(swapped16)); + Assert.AreEqual(native16, BO.SwappedU16(swapped16)); + + Assert.AreEqual(native32, BO.SwappedS32(swapped32)); + Assert.AreEqual(native32, BO.SwappedU32(swapped32)); + + Assert.AreEqual(native64, BO.SwappedS64(swapped64)); + Assert.AreEqual(native64, BO.SwappedU64(swapped64)); + } + + [Test] + public void ReadLESigned16() + => TestReadLE(native16, 2, BO.ReadLEShort); + + [Test] + public void ReadLESigned32() + => TestReadLE(native32,4, BO.ReadLEInt); + + [Test] + public void ReadLESigned64() + => TestReadLE(native64,8, BO.ReadLELong); + + [Test] + public void WriteLESigned16() + => TestWriteLE(swapped16, s => s.WriteLEShort(native16)); + + [Test] + public void WriteLESigned32() + => TestWriteLE(swapped32, s => s.WriteLEInt(native32)); + + [Test] + public void WriteLESigned64() + => TestWriteLE(swapped64, s => s.WriteLELong(native64)); + + [Test] + public void WriteLEUnsigned16() + => TestWriteLE(swapped16, s => s.WriteLEUshort((ushort)native16)); + + [Test] + public void WriteLEUnsigned32() + => TestWriteLE(swapped32, s => s.WriteLEUint(native32)); + + [Test] + public void WriteLEUnsigned64() + => TestWriteLE(swapped64, s => s.WriteLEUlong(native64)); + + [Test] + public async Task WriteLEAsyncSigned16() + => await TestWriteLEAsync(swapped16, (int)native16, BO.WriteLEShortAsync); + + [Test] + public async Task WriteLEAsyncUnsigned16() + => await TestWriteLEAsync(swapped16, (ushort)native16, BO.WriteLEUshortAsync); + + [Test] + public async Task WriteLEAsyncSigned32() + => await TestWriteLEAsync(swapped32, native32, BO.WriteLEIntAsync); + [Test] + public async Task WriteLEAsyncUnsigned32() + => await TestWriteLEAsync(swapped32, (uint)native32, BO.WriteLEUintAsync); + + [Test] + public async Task WriteLEAsyncSigned64() + => await TestWriteLEAsync(swapped64, native64, BO.WriteLELongAsync); + [Test] + public async Task WriteLEAsyncUnsigned64() + => await TestWriteLEAsync(swapped64, (ulong)native64, BO.WriteLEUlongAsync); + + + private static void TestReadLE(T expected, int bytes, Func read) + { + using (var ms = new MemoryStream(swapped64, 8 - bytes, bytes)) + { + Assert.AreEqual(expected, read(ms)); + } + } + + private static void TestWriteLE(byte[] expected, Action write) + { + using (var ms = new MemoryStream()) + { + write(ms); + Assert.AreEqual(expected, ms.ToArray()); + } + } + + private static async Task TestWriteLEAsync(byte[] expected, T input, Func write) + { + using (var ms = new MemoryStream()) + { + await write(ms, input, CancellationToken.None); + Assert.AreEqual(expected, ms.ToArray()); + } + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj index 12183fcdd..4a46e84f2 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj +++ b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj @@ -5,7 +5,10 @@ netcoreapp3.1;net46 - 8 + true + ..\..\assets\ICSharpCode.SharpZipLib.snk + true + 8.0 @@ -25,4 +28,10 @@ + + + ICSharpCode.SharpZipLib.snk + + + diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs index 179202b44..d0d2f2175 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs @@ -2,6 +2,8 @@ using System; using System.IO; using System.Linq; +using System.Text; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.TestSupport { @@ -76,6 +78,12 @@ public static byte[] GetDummyBytes(int size, int seed = DefaultSeed) random.NextBytes(bytes); return bytes; } + + public static async Task WriteDummyDataAsync(Stream stream, int size = -1) + { + var bytes = GetDummyBytes(size); + await stream.WriteAsync(bytes, 0, bytes.Length); + } /// /// Returns a file reference with bytes of dummy data written to it diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs index 688b91dc3..fcc4fe9b8 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs @@ -1,5 +1,7 @@ +using System; using ICSharpCode.SharpZipLib.Zip; using System.IO; +using NUnit.Framework; namespace ICSharpCode.SharpZipLib.Tests.TestSupport { @@ -8,30 +10,57 @@ namespace ICSharpCode.SharpZipLib.Tests.TestSupport /// internal static class ZipTesting { + public static void AssertValidZip(Stream stream, string password = null, bool usesAes = true) + { + Assert.That(TestArchive(stream, password), "Archive did not pass ZipFile.TestArchive"); + + if (!string.IsNullOrEmpty(password) && usesAes) + { + Assert.Ignore("ZipInputStream does not support AES"); + } + + stream.Seek(0, SeekOrigin.Begin); + + Assert.DoesNotThrow(() => + { + using var zis = new ZipInputStream(stream){Password = password}; + while (zis.GetNextEntry() != null) + { + new StreamReader(zis).ReadToEnd(); + } + }, "Archive could not be read by ZipInputStream"); + } + /// /// Tests the archive. /// /// The data. + /// The password. /// - public static bool TestArchive(byte[] data) + public static bool TestArchive(byte[] data, string password = null) { - return TestArchive(data, null); + using var ms = new MemoryStream(data); + return TestArchive(new MemoryStream(data), password); } /// /// Tests the archive. /// - /// The data. + /// The data. /// The password. /// true if archive tests ok; false otherwise. - public static bool TestArchive(byte[] data, string password) + public static bool TestArchive(Stream stream, string password = null) { - using (MemoryStream ms = new MemoryStream(data)) - using (ZipFile zipFile = new ZipFile(ms)) + using var zipFile = new ZipFile(stream) { - zipFile.Password = password; - return zipFile.TestArchive(true); - } + IsStreamOwner = false, + Password = password, + }; + + return zipFile.TestArchive(true, TestStrategy.FindAllErrors, (status, message) => + { + if (!string.IsNullOrWhiteSpace(message)) TestContext.Out.WriteLine(message); + }); } } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index f2b3e7859..2d641370c 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -913,7 +913,10 @@ private void TestEncryptedDirectoryEntry(MemoryStream s, int aesKeySize) var ms2 = new MemoryStream(s.ToArray()); using (ZipFile zf = new ZipFile(ms2)) { - Assert.IsTrue(zf.TestArchive(true)); + Assert.IsTrue(zf.TestArchive(true, TestStrategy.FindAllErrors, + (status, message) => { + if (!string.IsNullOrWhiteSpace(message)) TestContext.Out.WriteLine(message); + })); } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs new file mode 100644 index 000000000..b693f205d --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs @@ -0,0 +1,102 @@ +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Tests.TestSupport; +using ICSharpCode.SharpZipLib.Zip; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.Zip +{ + [TestFixture] + public class ZipStreamAsyncTests + { + + [Test] + [Category("Zip")] + [Category("Async")] + public async Task WriteZipStreamUsingAsync() + { +#if NETCOREAPP3_1_OR_GREATER + await using var ms = new MemoryStream(); + + await using (var outStream = new ZipOutputStream(ms){IsStreamOwner = false}) + { + await outStream.PutNextEntryAsync(new ZipEntry("FirstFile")); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.PutNextEntryAsync(new ZipEntry("SecondFile")); + await Utils.WriteDummyDataAsync(outStream, 12); + } + + ZipTesting.AssertValidZip(ms); +#endif + } + + [Test] + [Category("Zip")] + [Category("Async")] + public async Task WriteZipStreamAsync () + { + using var ms = new MemoryStream(); + + using(var outStream = new ZipOutputStream(ms) { IsStreamOwner = false }) + { + await outStream.PutNextEntryAsync(new ZipEntry("FirstFile")); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.PutNextEntryAsync(new ZipEntry("SecondFile")); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.FinishAsync(CancellationToken.None); + } + + ZipTesting.AssertValidZip(ms); + } + + + [Test] + [Category("Zip")] + [Category("Async")] + public async Task WriteZipStreamWithAesAsync() + { + using var ms = new MemoryStream(); + var password = "f4ls3p0s1t1v3"; + + using (var outStream = new ZipOutputStream(ms){IsStreamOwner = false, Password = password}) + { + await outStream.PutNextEntryAsync(new ZipEntry("FirstFile"){AESKeySize = 256}); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.PutNextEntryAsync(new ZipEntry("SecondFile"){AESKeySize = 256}); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.FinishAsync(CancellationToken.None); + } + + ZipTesting.AssertValidZip(ms, password); + } + + [Test] + [Category("Zip")] + [Category("Async")] + public async Task WriteZipStreamWithZipCryptoAsync() + { + using var ms = new MemoryStream(); + var password = "f4ls3p0s1t1v3"; + + using (var outStream = new ZipOutputStream(ms){IsStreamOwner = false, Password = password}) + { + await outStream.PutNextEntryAsync(new ZipEntry("FirstFile"){AESKeySize = 0}); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.PutNextEntryAsync(new ZipEntry("SecondFile"){AESKeySize = 0}); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.FinishAsync(CancellationToken.None); + } + + ZipTesting.AssertValidZip(ms, password, false); + } + + } +} From 612969e574fd9d922314f24923792e343871f102 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 10 Oct 2021 02:21:22 +0200 Subject: [PATCH 132/162] feat(zip): better string encoding handling (#592) This replaces the global static ZipStrings singleton with instances of StringCodec, which will: - Remove encoding configuration from a shared global state - Allow for different defaults for input and output - Explicitly override the encodings used for ZipCrypto and zip archive comments (the one in the Central Directory, not the individual entry comments). - Use "Unicode" for new entries (unless overriden) - Make it much more clear (hopefully) how and why different encodings are used. --- .../Streams/DeflaterOutputStream.cs | 4 + src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 30 +- .../Zip/ZipConstants.cs | 43 --- src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 10 +- .../Zip/ZipEntryFactory.cs | 4 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 82 +++-- src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs | 10 +- .../Zip/ZipInputStream.cs | 9 +- .../Zip/ZipOutputStream.cs | 18 +- src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs | 299 ++++++++++-------- .../Zip/FastZipHandling.cs | 64 ++-- .../Zip/GeneralHandling.cs | 27 +- .../Zip/ZipStreamAsyncTests.cs | 5 +- 13 files changed, 319 insertions(+), 286 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs index fd4bb47af..1c54b6848 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs @@ -2,6 +2,7 @@ using System; using System.IO; using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; @@ -203,6 +204,9 @@ public bool CanPatchEntries /// protected byte[] AESAuthCode; + /// + public Encoding ZipCryptoEncoding { get; set; } = StringCodec.DefaultZipCryptoEncoding; + /// /// Encrypt a block of data /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 01725f4c3..13aedb021 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -345,6 +345,29 @@ public Deflater.CompressionLevel CompressionLevel set { compressionLevel_ = value; } } + /// + /// Reflects the opposite of the internal , setting it to false overrides the encoding used for reading and writing zip entries + /// + public bool UseUnicode + { + get => !_stringCodec.ForceZipLegacyEncoding; + set => _stringCodec.ForceZipLegacyEncoding = !value; + } + + /// Gets or sets the code page used for reading/writing zip file entries when unicode is disabled + public int LegacyCodePage + { + get => _stringCodec.CodePage; + set => _stringCodec.CodePage = value; + } + + /// + public StringCodec StringCodec + { + get => _stringCodec; + set => _stringCodec = value; + } + #endregion Properties #region Delegates @@ -456,7 +479,7 @@ private void CreateZip(Stream outputStream, string sourceDirectory, bool recurse NameTransform = new ZipNameTransform(sourceDirectory); sourceDirectory_ = sourceDirectory; - using (outputStream_ = new ZipOutputStream(outputStream)) + using (outputStream_ = new ZipOutputStream(outputStream, _stringCodec)) { outputStream_.SetLevel((int)CompressionLevel); outputStream_.IsStreamOwner = !leaveOpen; @@ -631,6 +654,10 @@ private void ProcessFile(object sender, ScanEventArgs e) using (FileStream stream = File.Open(e.Name, FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipEntry entry = entryFactory_.MakeFileEntry(e.Name); + if (_stringCodec.ForceZipLegacyEncoding) + { + entry.IsUnicodeText = false; + } // Set up AES encryption for the entry if required. ConfigureEntryEncryption(entry); @@ -967,6 +994,7 @@ private static bool NameIsValid(string name) private INameTransform extractNameTransform_; private UseZip64 useZip64_ = UseZip64.Dynamic; private CompressionLevel compressionLevel_ = CompressionLevel.DEFAULT_COMPRESSION; + private StringCodec _stringCodec = new StringCodec(); private string password_; diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs index eadf33901..6d4892d55 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs @@ -471,48 +471,5 @@ public static class ZipConstants public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24); #endregion Header Signatures - - /// - /// Default encoding used for string conversion. 0 gives the default system OEM code page. - /// Using the default code page isnt the full solution necessarily - /// there are many variable factors, codepage 850 is often a good choice for - /// European users, however be careful about compatability. - /// - [Obsolete("Use ZipStrings instead")] - public static int DefaultCodePage - { - get => ZipStrings.CodePage; - set => ZipStrings.CodePage = value; - } - - /// Deprecated wrapper for - [Obsolete("Use ZipStrings.ConvertToString instead")] - public static string ConvertToString(byte[] data, int count) - => ZipStrings.ConvertToString(data, count); - - /// Deprecated wrapper for - [Obsolete("Use ZipStrings.ConvertToString instead")] - public static string ConvertToString(byte[] data) - => ZipStrings.ConvertToString(data); - - /// Deprecated wrapper for - [Obsolete("Use ZipStrings.ConvertToStringExt instead")] - public static string ConvertToStringExt(int flags, byte[] data, int count) - => ZipStrings.ConvertToStringExt(flags, data, count); - - /// Deprecated wrapper for - [Obsolete("Use ZipStrings.ConvertToStringExt instead")] - public static string ConvertToStringExt(int flags, byte[] data) - => ZipStrings.ConvertToStringExt(flags, data); - - /// Deprecated wrapper for - [Obsolete("Use ZipStrings.ConvertToArray instead")] - public static byte[] ConvertToArray(string str) - => ZipStrings.ConvertToArray(str); - - /// Deprecated wrapper for - [Obsolete("Use ZipStrings.ConvertToArray instead")] - public static byte[] ConvertToArray(int flags, string str) - => ZipStrings.ConvertToArray(flags, str); } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index ffeee1883..b0bf15821 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Text; namespace ICSharpCode.SharpZipLib.Zip { @@ -150,7 +151,7 @@ private enum Known : byte /// The name passed is null /// public ZipEntry(string name) - : this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated) + : this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated, true) { } @@ -171,7 +172,7 @@ public ZipEntry(string name) /// internal ZipEntry(string name, int versionRequiredToExtract) : this(name, versionRequiredToExtract, ZipConstants.VersionMadeBy, - CompressionMethod.Deflated) + CompressionMethod.Deflated, true) { } @@ -182,6 +183,7 @@ internal ZipEntry(string name, int versionRequiredToExtract) /// Version and HostSystem Information /// Minimum required zip feature version required to extract this entry /// Compression method for this entry. + /// Whether the entry uses unicode for name and comment /// /// The name passed is null /// @@ -193,7 +195,7 @@ internal ZipEntry(string name, int versionRequiredToExtract) /// It is not generally useful, use the constructor specifying the name only. /// internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo, - CompressionMethod method) + CompressionMethod method, bool unicode) { if (name == null) { @@ -216,7 +218,7 @@ internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo, this.versionToExtract = (ushort)versionRequiredToExtract; this.method = method; - IsUnicodeText = ZipStrings.UseUnicode; + IsUnicodeText = unicode; } /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs index 1e40baaff..ccbb26968 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntryFactory.cs @@ -68,7 +68,7 @@ public enum TimeSetting public ZipEntryFactory() { nameTransform_ = new ZipNameTransform(); - isUnicodeText_ = ZipStrings.UseUnicode; + isUnicodeText_ = true; } /// @@ -162,7 +162,7 @@ public int SetAttributes } /// - /// Get set a value indicating whether unidoce text should be set on. + /// Get set a value indicating whether unicode text should be set on. /// public bool IsUnicodeText { diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index a07b19f0c..0a844916e 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -367,7 +367,7 @@ public string Password } else { - key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(value)); + key = PkzipClassic.GenerateKeys(ZipCryptoEncoding.GetBytes(value)); } rawPassword_ = value; @@ -390,6 +390,7 @@ private bool HaveKeys /// Opens a Zip file with the given name for reading. /// /// The name of the file to open. + /// /// The argument supplied is null. /// /// An i/o error occurs @@ -397,13 +398,18 @@ private bool HaveKeys /// /// The file doesn't contain a valid zip archive. /// - public ZipFile(string name) + public ZipFile(string name, StringCodec stringCodec = null) { name_ = name ?? throw new ArgumentNullException(nameof(name)); baseStream_ = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read); isStreamOwner = true; + if (stringCodec != null) + { + _stringCodec = stringCodec; + } + try { ReadEntries(); @@ -725,6 +731,21 @@ public ZipEntry this[int index] } } + + /// + public Encoding ZipCryptoEncoding + { + get => _stringCodec.ZipCryptoEncoding; + set => _stringCodec.ZipCryptoEncoding = value; + } + + /// + public StringCodec StringCodec + { + get => _stringCodec; + set => _stringCodec = value; + } + #endregion Properties #region Input Handling @@ -1189,6 +1210,8 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) throw new ZipException(string.Format("Version required to extract this entry is invalid ({0})", extractVersion)); } + var localEncoding = _stringCodec.ZipInputEncoding(localFlags); + // Local entry flags dont have reserved bit set on. if ((localFlags & (int)(GeneralBitFlags.ReservedPKware4 | GeneralBitFlags.ReservedPkware14 | GeneralBitFlags.ReservedPkware15)) != 0) { @@ -1281,7 +1304,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } // Name data has already been read convert it and compare. - string localName = ZipStrings.ConvertToStringExt(localFlags, nameData); + string localName = localEncoding.GetString(nameData); // Central directory and local entry name match if (localName != entry.Name) @@ -1577,11 +1600,11 @@ public void CommitUpdate() else { // Create an empty archive if none existed originally. - if (entries_.Length == 0) - { - byte[] theComment = (newComment_ != null) ? newComment_.RawComment : ZipStrings.ConvertToArray(comment_); - ZipFormat.WriteEndOfCentralDirectory(baseStream_, 0, 0, 0, theComment); - } + if (entries_.Length != 0) return; + byte[] theComment = (newComment_ != null) + ? newComment_.RawComment + : _stringCodec.ZipArchiveCommentEncoding.GetBytes(comment_); + ZipFormat.WriteEndOfCentralDirectory(baseStream_, 0, 0, 0, theComment); } } finally @@ -1614,7 +1637,7 @@ public void SetComment(string comment) CheckUpdating(); - newComment_ = new ZipString(comment); + newComment_ = new ZipString(comment, _stringCodec.ZipArchiveCommentEncoding); if (newComment_.RawLength > 0xffff) { @@ -2142,7 +2165,8 @@ private void WriteLocalEntryHeader(ZipUpdate update) WriteLEInt((int)entry.Size); } - byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); + var entryEncoding = _stringCodec.ZipInputEncoding(entry.Flags); + byte[] name = entryEncoding.GetBytes(entry.Name); if (name.Length > 0xFFFF) { @@ -2249,7 +2273,8 @@ private int WriteCentralDirectoryHeader(ZipEntry entry) WriteLEInt((int)entry.Size); } - byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); + var entryEncoding = _stringCodec.ZipInputEncoding(entry.Flags); + byte[] name = entryEncoding.GetBytes(entry.Name); if (name.Length > 0xFFFF) { @@ -3076,7 +3101,7 @@ private void RunUpdates() } } - byte[] theComment = (newComment_ != null) ? newComment_.RawComment : ZipStrings.ConvertToArray(comment_); + byte[] theComment = newComment_?.RawComment ?? _stringCodec.ZipArchiveCommentEncoding.GetBytes(comment_); ZipFormat.WriteEndOfCentralDirectory(workFile.baseStream_, updateCount_, sizeEntries, centralDirOffset, theComment); @@ -3469,7 +3494,7 @@ private void ReadEntries() byte[] comment = new byte[commentSize]; StreamUtils.ReadFully(baseStream_, comment); - comment_ = ZipStrings.ConvertToString(comment); + comment_ = _stringCodec.ZipArchiveCommentEncoding.GetString(comment); } else { @@ -3586,11 +3611,13 @@ private void ReadEntries() long offset = ReadLEUint(); byte[] buffer = new byte[Math.Max(nameLen, commentLen)]; + var entryEncoding = _stringCodec.ZipInputEncoding(bitFlags); StreamUtils.ReadFully(baseStream_, buffer, 0, nameLen); - string name = ZipStrings.ConvertToStringExt(bitFlags, buffer, nameLen); + string name = entryEncoding.GetString(buffer, 0, nameLen); + var unicode = entryEncoding.IsZipUnicode(); - var entry = new ZipEntry(name, versionToExtract, versionMadeBy, (CompressionMethod)method) + var entry = new ZipEntry(name, versionToExtract, versionMadeBy, (CompressionMethod)method, unicode) { Crc = crc & 0xffffffffL, Size = size & 0xffffffffL, @@ -3623,7 +3650,7 @@ private void ReadEntries() if (commentLen > 0) { StreamUtils.ReadFully(baseStream_, buffer, 0, commentLen); - entry.Comment = ZipStrings.ConvertToStringExt(bitFlags, buffer, commentLen); + entry.Comment = entryEncoding.GetString(buffer, 0, commentLen); } entries_[i] = entry; @@ -3767,7 +3794,7 @@ private static void WriteEncryptionHeader(Stream stream, long crcValue) private bool isDisposed_; private string name_; - private string comment_; + private string comment_ = string.Empty; private string rawPassword_; private Stream baseStream_; private bool isStreamOwner; @@ -3775,6 +3802,7 @@ private static void WriteEncryptionHeader(Stream stream, long crcValue) private ZipEntry[] entries_; private byte[] key; private bool isNewArchive_; + private StringCodec _stringCodec = ZipStrings.GetStringCodec(); // Default is dynamic which is not backwards compatible and can cause problems // with XP's built in compression which cant read Zip64 archives. @@ -3813,19 +3841,23 @@ private class ZipString /// Initialise a with a string. /// /// The textual string form. - public ZipString(string comment) + /// + public ZipString(string comment, Encoding encoding) { comment_ = comment; isSourceString_ = true; + _encoding = encoding; } /// /// Initialise a using a string in its binary 'raw' form. /// /// - public ZipString(byte[] rawString) + /// + public ZipString(byte[] rawString, Encoding encoding) { rawComment_ = rawString; + _encoding = encoding; } #endregion Constructors @@ -3834,10 +3866,7 @@ public ZipString(byte[] rawString) /// Get a value indicating the original source of data for this instance. /// True if the source was a string; false if the source was binary data. /// - public bool IsSourceString - { - get { return isSourceString_; } - } + public bool IsSourceString => isSourceString_; /// /// Get the length of the comment when represented as raw bytes. @@ -3882,7 +3911,7 @@ private void MakeTextAvailable() { if (comment_ == null) { - comment_ = ZipStrings.ConvertToString(rawComment_); + comment_ = _encoding.GetString(rawComment_); } } @@ -3890,7 +3919,7 @@ private void MakeBytesAvailable() { if (rawComment_ == null) { - rawComment_ = ZipStrings.ConvertToArray(comment_); + rawComment_ = _encoding.GetBytes(comment_); } } @@ -3899,7 +3928,7 @@ private void MakeBytesAvailable() /// /// The to convert to a string. /// The textual equivalent for the input value. - static public implicit operator string(ZipString zipString) + public static implicit operator string(ZipString zipString) { zipString.MakeTextAvailable(); return zipString.comment_; @@ -3910,6 +3939,7 @@ static public implicit operator string(ZipString zipString) private string comment_; private byte[] rawComment_; private readonly bool isSourceString_; + private readonly Encoding _encoding; #endregion Instance Fields } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs index 75f6b72d7..a37ab3031 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs @@ -48,7 +48,7 @@ internal static class ZipFormat // Write the local file header // TODO: ZipFormat.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage internal static int WriteLocalHeader(Stream stream, ZipEntry entry, out EntryPatchData patchData, - bool headerInfoAvailable, bool patchEntryHeader, long streamOffset) + bool headerInfoAvailable, bool patchEntryHeader, long streamOffset, StringCodec stringCodec) { patchData = new EntryPatchData(); @@ -95,7 +95,7 @@ internal static int WriteLocalHeader(Stream stream, ZipEntry entry, out EntryPat } } - byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); + byte[] name = stringCodec.ZipOutputEncoding.GetBytes(entry.Name); if (name.Length > 0xFFFF) { @@ -385,7 +385,7 @@ internal static void ReadDataDescriptor(Stream stream, bool zip64, DescriptorDat } } - internal static int WriteEndEntry(Stream stream, ZipEntry entry) + internal static int WriteEndEntry(Stream stream, ZipEntry entry, StringCodec stringCodec) { stream.WriteLEInt(ZipConstants.CentralHeaderSignature); stream.WriteLEShort((entry.HostSystem << 8) | entry.VersionMadeBy); @@ -415,7 +415,7 @@ internal static int WriteEndEntry(Stream stream, ZipEntry entry) stream.WriteLEInt((int)entry.Size); } - byte[] name = ZipStrings.ConvertToArray(entry.Flags, entry.Name); + byte[] name = stringCodec.ZipOutputEncoding.GetBytes(entry.Name); if (name.Length > 0xffff) { @@ -458,7 +458,7 @@ internal static int WriteEndEntry(Stream stream, ZipEntry entry) byte[] extra = ed.GetEntryData(); byte[] entryComment = !(entry.Comment is null) - ? ZipStrings.ConvertToArray(entry.Flags, entry.Comment) + ? stringCodec.ZipOutputEncoding.GetBytes(entry.Comment) : Empty.Array(); if (entryComment.Length > 0xffff) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs index cccac6639..1b5b0ad53 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs @@ -76,6 +76,7 @@ public class ZipInputStream : InflaterInputStream private CompressionMethod method; private int flags; private string password; + private readonly StringCodec _stringCodec = ZipStrings.GetStringCodec(); #endregion Instance Fields @@ -221,9 +222,11 @@ public ZipEntry GetNextEntry() byte[] buffer = new byte[nameLen]; inputBuffer.ReadRawBuffer(buffer); - string name = ZipStrings.ConvertToStringExt(flags, buffer); + var entryEncoding = _stringCodec.ZipInputEncoding(flags); + string name = entryEncoding.GetString(buffer); + var unicode = entryEncoding.IsZipUnicode(); - entry = new ZipEntry(name, versionRequiredToExtract, ZipConstants.VersionMadeBy, method) + entry = new ZipEntry(name, versionRequiredToExtract, ZipConstants.VersionMadeBy, method, unicode) { Flags = flags, }; @@ -524,7 +527,7 @@ private int InitialRead(byte[] destination, int offset, int count) // Generate and set crypto transform... var managed = new PkzipClassicManaged(); - byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password)); + byte[] key = PkzipClassic.GenerateKeys(_stringCodec.ZipCryptoEncoding.GetBytes(password)); inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 7aa3295fe..0b292fb3f 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -80,6 +80,11 @@ public ZipOutputStream(Stream baseOutputStream, int bufferSize) { } + internal ZipOutputStream(Stream baseOutputStream, StringCodec stringCodec) : this(baseOutputStream) + { + _stringCodec = stringCodec; + } + #endregion Constructors /// @@ -105,8 +110,7 @@ public bool IsFinished /// public void SetComment(string comment) { - // TODO: Its not yet clear how to handle unicode comments here. - byte[] commentBytes = ZipStrings.ConvertToArray(comment); + byte[] commentBytes = _stringCodec.ZipArchiveCommentEncoding.GetBytes(comment); if (commentBytes.Length > 0xffff) { throw new ArgumentOutOfRangeException(nameof(comment)); @@ -392,7 +396,7 @@ internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0) // Write the local file header offset += ZipFormat.WriteLocalHeader(stream, entry, out var entryPatchData, - headerInfoAvailable, patchEntryHeader, streamOffset); + headerInfoAvailable, patchEntryHeader, streamOffset, _stringCodec); patchData = entryPatchData; @@ -652,7 +656,7 @@ private byte[] CreateZipCryptoHeader(long crcValue) private void InitializeZipCryptoPassword(string password) { var pkManaged = new PkzipClassicManaged(); - byte[] key = PkzipClassic.GenerateKeys(ZipStrings.ConvertToArray(password)); + byte[] key = PkzipClassic.GenerateKeys(ZipCryptoEncoding.GetBytes(password)); cryptoTransform_ = pkManaged.CreateEncryptor(key, null); } @@ -765,7 +769,7 @@ public override void Finish() foreach (var entry in entries) { - sizeEntries += ZipFormat.WriteEndEntry(baseOutputStream_, entry); + sizeEntries += ZipFormat.WriteEndEntry(baseOutputStream_, entry, _stringCodec); } ZipFormat.WriteEndOfCentralDirectory(baseOutputStream_, numEntries, sizeEntries, offset, zipComment); @@ -795,7 +799,7 @@ public override async Task FinishAsync(CancellationToken ct) { await baseOutputStream_.WriteProcToStreamAsync(ms, s => { - sizeEntries += ZipFormat.WriteEndEntry(s, entry); + sizeEntries += ZipFormat.WriteEndEntry(s, entry, _stringCodec); }, ct); } @@ -880,6 +884,8 @@ public override void Flush() /// private string password; + private readonly StringCodec _stringCodec = ZipStrings.GetStringCodec(); + #endregion Instance Fields #region Static Fields diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs index 2d0c4cff4..29fa98014 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipStrings.cs @@ -4,191 +4,210 @@ namespace ICSharpCode.SharpZipLib.Zip { + internal static class EncodingExtensions + { + public static bool IsZipUnicode(this Encoding e) + => e.Equals(StringCodec.UnicodeZipEncoding); + } + /// - /// This static class contains functions for encoding and decoding zip file strings + /// Deprecated way of setting zip encoding provided for backwards compability. + /// Use when possible. /// + /// + /// If any ZipStrings properties are being modified, it will enter a backwards compatibility mode, mimicking the + /// old behaviour where a single instance was shared between all Zip* instances. + /// public static class ZipStrings { - static ZipStrings() + static readonly StringCodec CompatCodec = new StringCodec(); + + private static bool compatibilityMode; + + /// + /// Returns a new instance or the shared backwards compatible instance. + /// + /// + public static StringCodec GetStringCodec() + => compatibilityMode ? CompatCodec : new StringCodec(); + + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static int CodePage { - try + get => CompatCodec.CodePage; + set { - var platformCodepage = Encoding.GetEncoding(0).CodePage; - SystemDefaultCodePage = (platformCodepage == 1 || platformCodepage == 2 || platformCodepage == 3 || platformCodepage == 42) ? FallbackCodePage : platformCodepage; + CompatCodec.CodePage = value; + compatibilityMode = true; } - catch + } + + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static int SystemDefaultCodePage => StringCodec.SystemDefaultCodePage; + + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static bool UseUnicode + { + get => !CompatCodec.ForceZipLegacyEncoding; + set { - SystemDefaultCodePage = FallbackCodePage; + CompatCodec.ForceZipLegacyEncoding = !value; + compatibilityMode = true; } } - /// Code page backing field - /// - /// The original Zip specification (https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) states - /// that file names should only be encoded with IBM Code Page 437 or UTF-8. - /// In practice, most zip apps use OEM or system encoding (typically cp437 on Windows). - /// Let's be good citizens and default to UTF-8 http://utf8everywhere.org/ - /// - private static int codePage = AutomaticCodePage; + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + private static bool HasUnicodeFlag(int flags) + => ((GeneralBitFlags)flags).HasFlag(GeneralBitFlags.UnicodeText); + + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static string ConvertToString(byte[] data, int count) + => CompatCodec.ZipOutputEncoding.GetString(data, 0, count); - /// Automatically select codepage while opening archive - /// see https://github.com/icsharpcode/SharpZipLib/pull/280#issuecomment-433608324 - /// - private const int AutomaticCodePage = -1; + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static string ConvertToString(byte[] data) + => CompatCodec.ZipOutputEncoding.GetString(data); + + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static string ConvertToStringExt(int flags, byte[] data, int count) + => CompatCodec.ZipEncoding(HasUnicodeFlag(flags)).GetString(data, 0, count); - /// - /// Encoding used for string conversion. Setting this to 65001 (UTF-8) will - /// also set the Language encoding flag to indicate UTF-8 encoded file names. - /// - public static int CodePage + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static string ConvertToStringExt(int flags, byte[] data) + => CompatCodec.ZipEncoding(HasUnicodeFlag(flags)).GetString(data); + + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static byte[] ConvertToArray(string str) + => ConvertToArray(0, str); + + /// + [Obsolete("Use ZipFile/Zip*Stream StringCodec instead")] + public static byte[] ConvertToArray(int flags, string str) + => (string.IsNullOrEmpty(str)) + ? Empty.Array() + : CompatCodec.ZipEncoding(HasUnicodeFlag(flags)).GetBytes(str); + } + + /// + /// Utility class for resolving the encoding used for reading and writing strings + /// + public class StringCodec + { + static StringCodec() { - get + try { - return codePage == AutomaticCodePage? Encoding.UTF8.CodePage:codePage; + var platformCodepage = Encoding.Default.CodePage; + SystemDefaultCodePage = (platformCodepage == 1 || platformCodepage == 2 || platformCodepage == 3 || platformCodepage == 42) ? FallbackCodePage : platformCodepage; } - set + catch { - if ((value < 0) || (value > 65535) || - (value == 1) || (value == 2) || (value == 3) || (value == 42)) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } - - codePage = value; + SystemDefaultCodePage = FallbackCodePage; } + + SystemDefaultEncoding = Encoding.GetEncoding(SystemDefaultCodePage); } - private const int FallbackCodePage = 437; + /// + /// If set, use the encoding set by for zip entries instead of the defaults + /// + public bool ForceZipLegacyEncoding { get; set; } /// - /// Attempt to get the operating system default codepage, or failing that, to - /// the fallback code page IBM 437. + /// The default encoding used for ZipCrypto passwords in zip files, set to + /// for greatest compability. /// - public static int SystemDefaultCodePage { get; } + public static Encoding DefaultZipCryptoEncoding => SystemDefaultEncoding; + + /// + /// Returns the encoding for an output . + /// Unless overriden by it returns . + /// + public Encoding ZipOutputEncoding => ZipEncoding(!ForceZipLegacyEncoding); /// - /// Get whether the default codepage is set to UTF-8. Setting this property to false will - /// set the to + /// Returns if is set, otherwise it returns the encoding indicated by /// + public Encoding ZipEncoding(bool unicode) => unicode ? UnicodeZipEncoding : _legacyEncoding; + + /// + /// Returns the appropriate encoding for an input according to . + /// If overridden by , it always returns the encoding indicated by . + /// + /// + /// + public Encoding ZipInputEncoding(GeneralBitFlags flags) => ZipInputEncoding((int)flags); + + /// + public Encoding ZipInputEncoding(int flags) => ZipEncoding(!ForceZipLegacyEncoding && (flags & (int)GeneralBitFlags.UnicodeText) != 0); + + /// Code page encoding, used for non-unicode strings /// - /// Get OEM codepage from NetFX, which parses the NLP file with culture info table etc etc. - /// But sometimes it yields the special value of 1 which is nicknamed CodePageNoOEM in sources (might also mean CP_OEMCP, but Encoding puts it so). - /// This was observed on Ukranian and Hindu systems. - /// Given this value, throws an . - /// So replace it with , (IBM 437 which is the default code page in a default Windows installation console. + /// The original Zip specification (https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT) states + /// that file names should only be encoded with IBM Code Page 437 or UTF-8. + /// In practice, most zip apps use OEM or system encoding (typically cp437 on Windows). + /// Let's be good citizens and default to UTF-8 http://utf8everywhere.org/ /// - public static bool UseUnicode - { - get - { - return codePage == Encoding.UTF8.CodePage; - } - set - { - if (value) - { - codePage = Encoding.UTF8.CodePage; - } - else - { - codePage = SystemDefaultCodePage; - } - } - } + private Encoding _legacyEncoding = SystemDefaultEncoding; + + private Encoding _zipArchiveCommentEncoding; + private Encoding _zipCryptoEncoding; /// - /// Convert a portion of a byte array to a string using + /// Returns the UTF-8 code page (65001) used for zip entries with unicode flag set /// - /// - /// Data to convert to string - /// - /// - /// Number of bytes to convert starting from index 0 - /// - /// - /// data[0]..data[count - 1] converted to a string - /// - public static string ConvertToString(byte[] data, int count) - => data == null - ? string.Empty - : Encoding.GetEncoding(CodePage).GetString(data, 0, count); + public static readonly Encoding UnicodeZipEncoding = Encoding.UTF8; /// - /// Convert a byte array to a string using + /// Code page used for non-unicode strings and legacy zip encoding (if is set). + /// Default value is /// - /// - /// Byte array to convert - /// - /// - /// dataconverted to a string - /// - public static string ConvertToString(byte[] data) - => ConvertToString(data, data.Length); - - private static Encoding EncodingFromFlag(int flags) - => ((flags & (int)GeneralBitFlags.UnicodeText) != 0) - ? Encoding.UTF8 - : Encoding.GetEncoding( - // if CodePage wasn't set manually and no utf flag present - // then we must use SystemDefault (old behavior) - // otherwise, CodePage should be preferred over SystemDefault - // see https://github.com/icsharpcode/SharpZipLib/issues/274 - codePage == AutomaticCodePage? - SystemDefaultCodePage: - codePage); + public int CodePage + { + get => _legacyEncoding.CodePage; + set => _legacyEncoding = (value < 4 || value > 65535 || value == 42) + ? throw new ArgumentOutOfRangeException(nameof(value)) + : Encoding.GetEncoding(value); + } + + private const int FallbackCodePage = 437; /// - /// Convert a byte array to a string using + /// Operating system default codepage, or if it could not be retrieved, the fallback code page IBM 437. /// - /// The applicable general purpose bits flags - /// - /// Byte array to convert - /// - /// The number of bytes to convert. - /// - /// dataconverted to a string - /// - public static string ConvertToStringExt(int flags, byte[] data, int count) - => (data == null) - ? string.Empty - : EncodingFromFlag(flags).GetString(data, 0, count); + public static int SystemDefaultCodePage { get; } /// - /// Convert a byte array to a string using + /// The system default encoding, based on /// - /// - /// Byte array to convert - /// - /// The applicable general purpose bits flags - /// - /// dataconverted to a string - /// - public static string ConvertToStringExt(int flags, byte[] data) - => ConvertToStringExt(flags, data, data.Length); + public static Encoding SystemDefaultEncoding { get; } /// - /// Convert a string to a byte array using + /// The encoding used for the zip archive comment. Defaults to the encoding for , since + /// no unicode flag can be set for it in the files. /// - /// - /// String to convert to an array - /// - /// Converted array - public static byte[] ConvertToArray(string str) - => str == null - ? Empty.Array() - : Encoding.GetEncoding(CodePage).GetBytes(str); + public Encoding ZipArchiveCommentEncoding + { + get => _zipArchiveCommentEncoding ?? _legacyEncoding; + set => _zipArchiveCommentEncoding = value; + } /// - /// Convert a string to a byte array using + /// The encoding used for the ZipCrypto passwords. Defaults to . /// - /// The applicable general purpose bits flags - /// - /// String to convert to an array - /// - /// Converted array - public static byte[] ConvertToArray(int flags, string str) - => (string.IsNullOrEmpty(str)) - ? Empty.Array() - : EncodingFromFlag(flags).GetBytes(str); + public Encoding ZipCryptoEncoding + { + get => _zipCryptoEncoding ?? DefaultZipCryptoEncoding; + set => _zipCryptoEncoding = value; + } } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index f1c9863da..90b5784ff 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -239,9 +239,14 @@ public void CreateExceptions() #region String testing helper - private void TestFileNames(IReadOnlyList names) + private void TestFileNames(int codePage, IReadOnlyList names) { var zippy = new FastZip(); + if (codePage > 0) + { + zippy.UseUnicode = false; + zippy.LegacyCodePage = codePage; + } using var tempDir = Utils.GetTempDir(); using var tempZip = Utils.GetTempFile(); @@ -254,7 +259,7 @@ private void TestFileNames(IReadOnlyList names) zippy.CreateZip(tempZip, tempDir, recurse: true, fileFilter: null); - using var zf = new ZipFile(tempZip); + using var zf = new ZipFile(tempZip, zippy.StringCodec); Assert.AreEqual(nameCount, zf.Count); foreach (var name in names) { @@ -264,7 +269,7 @@ private void TestFileNames(IReadOnlyList names) var entry = zf[index]; - if (ZipStrings.UseUnicode) + if (zippy.UseUnicode) { Assert.IsTrue(entry.IsUnicodeText, "Zip entry #{0} not marked as unicode", index); } @@ -288,15 +293,7 @@ private void TestFileNames(IReadOnlyList names) [Category("Unicode")] public void UnicodeText() { - var preCp = ZipStrings.CodePage; - try - { - TestFileNames(StringTesting.Filenames.ToArray()); - } - finally - { - ZipStrings.CodePage = preCp; - } + TestFileNames(0, StringTesting.Filenames.ToArray()); } [Test] @@ -304,35 +301,26 @@ public void UnicodeText() [Category("Unicode")] public void NonUnicodeText() { - var preCp = ZipStrings.CodePage; - try - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - foreach (var (language, filename, encoding) in StringTesting.TestSamples) + foreach (var (language, filename, encoding) in StringTesting.TestSamples) + { + Console.WriteLine($"{language} filename \"{filename}\" using \"{encoding}\":"); + + // TODO: samples of this test must be reversible + // Some samples can't be restored back with their encoding. + // test wasn't failing only because SystemDefaultCodepage is 65001 on Net.Core and + // old behaviour actually was using Unicode instead of user's passed codepage + var encoder = Encoding.GetEncoding(encoding); + var bytes = encoder.GetBytes(filename); + var restoredString = encoder.GetString(bytes); + if(string.CompareOrdinal(filename, restoredString) != 0) { - Console.WriteLine($"{language} filename \"{filename}\" using \"{encoding}\":"); - - // TODO: samples of this test must be reversible - // Some samples can't be restored back with their encoding. - // test wasn't failing only because SystemDefaultCodepage is 65001 on Net.Core and - // old behaviour actually was using Unicode instead of user's passed codepage - var encoder = Encoding.GetEncoding(encoding); - var bytes = encoder.GetBytes(filename); - var restoredString = encoder.GetString(bytes); - if(string.CompareOrdinal(filename, restoredString) != 0) - { - Console.WriteLine($"Sample for language {language} with value of {filename} is skipped, because it's irreversable"); - continue; - } - - ZipStrings.CodePage = Encoding.GetEncoding(encoding).CodePage; - TestFileNames(new []{filename}); + Console.WriteLine($"Sample for language {language} with value of {filename} is skipped, because it's irreversable"); + continue; } - } - finally - { - ZipStrings.CodePage = preCp; + + TestFileNames(Encoding.GetEncoding(encoding).CodePage, new [] { filename }); } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs index c3e32064c..ad97563aa 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs @@ -856,20 +856,17 @@ private object UnZipZeroLength(byte[] zipped) return result; } - private void CheckNameConversion(string toCheck) - { - byte[] intermediate = ZipStrings.ConvertToArray(toCheck); - string final = ZipStrings.ConvertToString(intermediate); - - Assert.AreEqual(toCheck, final, "Expected identical result"); - } - [Test] [Category("Zip")] - public void NameConversion() + [TestCase("Hello")] + [TestCase("a/b/c/d/e/f/g/h/SomethingLikeAnArchiveName.txt")] + public void LegacyNameConversion(string name) { - CheckNameConversion("Hello"); - CheckNameConversion("a/b/c/d/e/f/g/h/SomethingLikeAnArchiveName.txt"); + var encoding = new StringCodec().ZipEncoding(false); + byte[] intermediate = encoding.GetBytes(name); + string final = encoding.GetString(intermediate); + + Assert.AreEqual(name, final, "Expected identical result"); } [Test] @@ -878,22 +875,22 @@ public void UnicodeNameConversion() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - ZipStrings.CodePage = 850; + var codec = new StringCodec() {CodePage = 850}; string sample = "Hello world"; byte[] rawData = Encoding.ASCII.GetBytes(sample); - string converted = ZipStrings.ConvertToStringExt(0, rawData); + var converted = codec.ZipInputEncoding(0).GetString(rawData); Assert.AreEqual(sample, converted); - converted = ZipStrings.ConvertToStringExt((int)GeneralBitFlags.UnicodeText, rawData); + converted = codec.ZipInputEncoding((int)GeneralBitFlags.UnicodeText).GetString(rawData); Assert.AreEqual(sample, converted); // This time use some greek characters sample = "\u03A5\u03d5\u03a3"; rawData = Encoding.UTF8.GetBytes(sample); - converted = ZipStrings.ConvertToStringExt((int)GeneralBitFlags.UnicodeText, rawData); + converted = codec.ZipInputEncoding((int)GeneralBitFlags.UnicodeText).GetString(rawData); Assert.AreEqual(sample, converted); } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs index b693f205d..5eb33c063 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs @@ -10,13 +10,12 @@ namespace ICSharpCode.SharpZipLib.Tests.Zip [TestFixture] public class ZipStreamAsyncTests { - +#if NETCOREAPP3_1_OR_GREATER [Test] [Category("Zip")] [Category("Async")] public async Task WriteZipStreamUsingAsync() { -#if NETCOREAPP3_1_OR_GREATER await using var ms = new MemoryStream(); await using (var outStream = new ZipOutputStream(ms){IsStreamOwner = false}) @@ -29,8 +28,8 @@ public async Task WriteZipStreamUsingAsync() } ZipTesting.AssertValidZip(ms); -#endif } +#endif [Test] [Category("Zip")] From ff64d0ae51162ee2ce84a4621c7a1ec667ca49a9 Mon Sep 17 00:00:00 2001 From: Temtaime Date: Thu, 18 Nov 2021 02:30:12 +0300 Subject: [PATCH 133/162] feat(zip): enable ZipOuputStream to write precompressed files (#683) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: nils måsén --- .../Zip/ZipOutputStream.cs | 129 +++++++++++++--- .../Zip/GeneralHandling.cs | 4 +- .../Zip/PassthroughTests.cs | 140 ++++++++++++++++++ 3 files changed, 250 insertions(+), 23 deletions(-) create mode 100644 test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 0b292fb3f..36349c886 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -270,7 +270,76 @@ public void PutNextEntry(ZipEntry entry) WriteOutput(GetEntryEncryptionHeader(entry)); } } - + + /// + /// Starts a new passthrough Zip entry. It automatically closes the previous + /// entry if present. + /// Passthrough entry is an entry that is created from compressed data. + /// It is useful to avoid recompression to save CPU resources if compressed data is already disposable. + /// All entry elements bar name, crc, size and compressed size are optional, but must be correct if present. + /// Compression should be set to Deflated. + /// + /// + /// the entry. + /// + /// + /// if entry passed is null. + /// + /// + /// if an I/O error occurred. + /// + /// + /// if stream was finished. + /// + /// + /// Crc is not set
+ /// Size is not set
+ /// CompressedSize is not set
+ /// CompressionMethod is not Deflate
+ /// Too many entries in the Zip file
+ /// Entry name is too long
+ /// Finish has already been called
+ ///
+ /// + /// The Compression method specified for the entry is unsupported
+ /// Entry is encrypted
+ ///
+ public void PutNextPassthroughEntry(ZipEntry entry) + { + if(curEntry != null) + { + CloseEntry(); + } + + if(entry.Crc < 0) + { + throw new ZipException("Crc must be set for passthrough entry"); + } + + if(entry.Size < 0) + { + throw new ZipException("Size must be set for passthrough entry"); + } + + if(entry.CompressedSize < 0) + { + throw new ZipException("CompressedSize must be set for passthrough entry"); + } + + if(entry.CompressionMethod != CompressionMethod.Deflated) + { + throw new NotImplementedException("Only Deflated entries are supported for passthrough"); + } + + if(!string.IsNullOrEmpty(Password)) + { + throw new NotImplementedException("Encrypted passthrough entries are not supported"); + } + + PutNextEntry(baseOutputStream_, entry, 0, true); + } + + private void WriteOutput(byte[] bytes) => baseOutputStream_.Write(bytes, 0, bytes.Length); @@ -282,7 +351,7 @@ private byte[] GetEntryEncryptionHeader(ZipEntry entry) => ? InitializeAESPassword(entry, Password) : CreateZipCryptoHeader(entry.Crc < 0 ? entry.DosTime << 16 : entry.Crc); - internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0) + internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0, bool passthroughEntry = false) { if (entry == null) { @@ -313,6 +382,8 @@ internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0) throw new InvalidOperationException("The Password property must be set before AES encrypted entries can be added"); } + entryIsPassthrough = passthroughEntry; + int compressionLevel = defaultCompressionLevel; // Clear flags that the library manages internally @@ -322,7 +393,7 @@ internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0) bool headerInfoAvailable; // No need to compress - definitely no data. - if (entry.Size == 0) + if (entry.Size == 0 && !entryIsPassthrough) { entry.CompressedSize = entry.Size; entry.Crc = 0; @@ -406,14 +477,17 @@ internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0) // Activate the entry. curEntry = entry; + size = 0; + + if(entryIsPassthrough) + return; + crc.Reset(); if (method == CompressionMethod.Deflated) { deflater_.Reset(); deflater_.SetLevel(compressionLevel); } - size = 0; - } /// @@ -506,6 +580,17 @@ internal void WriteEntryFooter(Stream stream) throw new InvalidOperationException("No open entry"); } + if(entryIsPassthrough) + { + if(curEntry.CompressedSize != size) + { + throw new ZipException($"compressed size was {size}, but {curEntry.CompressedSize} expected"); + } + + offset += size; + return; + } + long csize = size; // First finish the deflater, if appropriate @@ -695,30 +780,28 @@ public override void Write(byte[] buffer, int offset, int count) throw new ArgumentException("Invalid offset/count combination"); } - if (curEntry.AESKeySize == 0) + if (curEntry.AESKeySize == 0 && !entryIsPassthrough) { - // Only update CRC if AES is not enabled + // Only update CRC if AES is not enabled and entry is not a passthrough one crc.Update(new ArraySegment(buffer, offset, count)); } size += count; - switch (curMethod) + if(curMethod == CompressionMethod.Stored || entryIsPassthrough) { - case CompressionMethod.Deflated: - base.Write(buffer, offset, count); - break; - - case CompressionMethod.Stored: - if (Password != null) - { - CopyAndEncrypt(buffer, offset, count); - } - else - { - baseOutputStream_.Write(buffer, offset, count); - } - break; + if (Password != null) + { + CopyAndEncrypt(buffer, offset, count); + } + else + { + baseOutputStream_.Write(buffer, offset, count); + } + } + else + { + base.Write(buffer, offset, count); } } @@ -844,6 +927,8 @@ public override void Flush() /// private ZipEntry curEntry; + private bool entryIsPassthrough; + private int defaultCompressionLevel = Deflater.DEFAULT_COMPRESSION; private CompressionMethod curMethod = CompressionMethod.Deflated; diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs index ad97563aa..e16a82967 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs @@ -1,5 +1,7 @@ -using ICSharpCode.SharpZipLib.Tests.TestSupport; +using ICSharpCode.SharpZipLib.Checksum; +using ICSharpCode.SharpZipLib.Tests.TestSupport; using ICSharpCode.SharpZipLib.Zip; +using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using NUnit.Framework; using System; using System.IO; diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs new file mode 100644 index 000000000..1a4b266f2 --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs @@ -0,0 +1,140 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Text; +using ICSharpCode.SharpZipLib.Checksum; +using ICSharpCode.SharpZipLib.Tests.TestSupport; +using ICSharpCode.SharpZipLib.Zip; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.Zip +{ + [TestFixture] + public class PassthroughTests + { + [Test] + [Category("Zip")] + public void AddingValidPrecompressedEntryToZipOutputStream() + { + using var ms = new MemoryStream(); + + using (var outStream = new ZipOutputStream(ms){IsStreamOwner = false}) + { + var (compressedData, crc, size) = CreateDeflatedData(); + var entry = new ZipEntry("dummyfile.tst") + { + CompressionMethod = CompressionMethod.Deflated, + Size = size, + Crc = (uint)crc.Value, + CompressedSize = compressedData.Length, + }; + + outStream.PutNextPassthroughEntry(entry); + + compressedData.CopyTo(outStream); + } + + Assert.IsTrue(ZipTesting.TestArchive(ms.ToArray())); + } + + private static (MemoryStream, Crc32, int) CreateDeflatedData() + { + var data = Encoding.UTF8.GetBytes("Hello, world"); + + var crc = new Crc32(); + crc.Update(data); + + var compressedData = new MemoryStream(); + using(var gz = new DeflateStream(compressedData, CompressionMode.Compress, leaveOpen: true)) + { + gz.Write(data, 0, data.Length); + } + compressedData.Position = 0; + + return (compressedData, crc, data.Length); + } + + [Test] + [Category("Zip")] + public void AddingPrecompressedEntryToZipOutputStreamWithInvalidSize() + { + using var outStream = new ZipOutputStream(new MemoryStream()); + var (compressedData, crc, size) = CreateDeflatedData(); + outStream.Password = "mockpassword"; + var entry = new ZipEntry("dummyfile.tst") + { + CompressionMethod = CompressionMethod.Stored, + Crc = (uint)crc.Value, + CompressedSize = compressedData.Length, + }; + + Assert.Throws(() => + { + outStream.PutNextPassthroughEntry(entry); + }); + } + + + [Test] + [Category("Zip")] + public void AddingPrecompressedEntryToZipOutputStreamWithInvalidCompressedSize() + { + using var outStream = new ZipOutputStream(new MemoryStream()); + var (compressedData, crc, size) = CreateDeflatedData(); + outStream.Password = "mockpassword"; + var entry = new ZipEntry("dummyfile.tst") + { + CompressionMethod = CompressionMethod.Stored, + Size = size, + Crc = (uint)crc.Value, + }; + + Assert.Throws(() => + { + outStream.PutNextPassthroughEntry(entry); + }); + } + + [Test] + [Category("Zip")] + public void AddingPrecompressedEntryToZipOutputStreamWithNonSupportedMethod() + { + using var outStream = new ZipOutputStream(new MemoryStream()); + var (compressedData, crc, size) = CreateDeflatedData(); + outStream.Password = "mockpassword"; + var entry = new ZipEntry("dummyfile.tst") + { + CompressionMethod = CompressionMethod.LZMA, + Size = size, + Crc = (uint)crc.Value, + CompressedSize = compressedData.Length, + }; + + Assert.Throws(() => + { + outStream.PutNextPassthroughEntry(entry); + }); + } + + [Test] + [Category("Zip")] + public void AddingPrecompressedEntryToZipOutputStreamWithEncryption() + { + using var outStream = new ZipOutputStream(new MemoryStream()); + var (compressedData, crc, size) = CreateDeflatedData(); + outStream.Password = "mockpassword"; + var entry = new ZipEntry("dummyfile.tst") + { + CompressionMethod = CompressionMethod.Deflated, + Size = size, + Crc = (uint)crc.Value, + CompressedSize = compressedData.Length, + }; + + Assert.Throws(() => + { + outStream.PutNextPassthroughEntry(entry); + }); + } + } +} From b368847ac1f2625f0ccf7af733ff0a1eaf54a1c1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Feb 2022 10:35:46 +0100 Subject: [PATCH 134/162] Bump SharpZipLib in /samples/ICSharpCode.SharpZipLib.Samples/cs/sz (#716) Bumps [SharpZipLib](https://github.com/icsharpcode/SharpZipLib) from 1.3.1 to 1.3.3. - [Release notes](https://github.com/icsharpcode/SharpZipLib/releases) - [Changelog](https://github.com/icsharpcode/SharpZipLib/blob/master/docs/Changes.txt) - [Commits](https://github.com/icsharpcode/SharpZipLib/compare/v1.3.1...v1.3.3) --- updated-dependencies: - dependency-name: SharpZipLib dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj index 02a096db6..121d55859 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/sz/sz.csproj @@ -85,7 +85,7 @@ - 1.3.1 + 1.3.3 From ca8c6de7219feb48724e20923b89c9d2f99d166a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Feb 2022 10:36:10 +0100 Subject: [PATCH 135/162] Bump SharpZipLib (#715) Bumps [SharpZipLib](https://github.com/icsharpcode/SharpZipLib) from 1.3.1 to 1.3.3. - [Release notes](https://github.com/icsharpcode/SharpZipLib/releases) - [Changelog](https://github.com/icsharpcode/SharpZipLib/blob/master/docs/Changes.txt) - [Commits](https://github.com/icsharpcode/SharpZipLib/compare/v1.3.1...v1.3.3) --- updated-dependencies: - dependency-name: SharpZipLib dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .../vb/minibzip2/minibzip2.vbproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj index 618adb8ad..e15a05ec6 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/minibzip2/minibzip2.vbproj @@ -112,7 +112,7 @@ - 1.3.1 + 1.3.3 From 9e0d4a434d1bea71c7a9c3c564da43b25db84b17 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 2 Feb 2022 10:36:39 +0100 Subject: [PATCH 136/162] Bump SharpZipLib in /samples/ICSharpCode.SharpZipLib.Samples/cs/zf (#711) Bumps [SharpZipLib](https://github.com/icsharpcode/SharpZipLib) from 1.3.1 to 1.3.3. - [Release notes](https://github.com/icsharpcode/SharpZipLib/releases) - [Changelog](https://github.com/icsharpcode/SharpZipLib/blob/master/docs/Changes.txt) - [Commits](https://github.com/icsharpcode/SharpZipLib/compare/v1.3.1...v1.3.3) --- updated-dependencies: - dependency-name: SharpZipLib dependency-type: direct:production ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj index e8d8b757f..1dbf75744 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/zf/zf.csproj @@ -85,7 +85,7 @@ - 1.3.1 + 1.3.3 From 3677a63af4f10bbb9ca6d86fcffae9e4f87e1979 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 10 Feb 2022 17:19:27 +0100 Subject: [PATCH 137/162] fix(samples): bump lib versions to v1.3.3 (#720) --- .../cs/Cmd_BZip2/Cmd_BZip2.csproj | 2 +- .../cs/Cmd_Checksum/Cmd_Checksum.csproj | 2 +- .../ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj | 2 +- .../ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj | 2 +- .../cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj | 2 +- .../cs/CreateZipFile/CreateZipFile.csproj | 2 +- .../ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj | 2 +- .../cs/unzipfile/unzipfile.csproj | 2 +- .../cs/viewzipfile/viewzipfile.csproj | 2 +- .../vb/CreateZipFile/CreateZipFile.vbproj | 2 +- .../vb/WpfCreateZipFile/WpfCreateZipFile.vbproj | 2 +- .../vb/viewzipfile/viewzipfile.vbproj | 2 +- .../vb/zipfiletest/zipfiletest.vbproj | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj index 07039ab9d..b1536ff0f 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_BZip2/Cmd_BZip2.csproj @@ -101,7 +101,7 @@ copy Cmd_BZip2.exe bunzip2.exe - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj index 1509d6080..d5d9f6cfe 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Checksum/Cmd_Checksum.csproj @@ -100,7 +100,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj index d5e021825..9ebaa8ca6 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_GZip/Cmd_GZip.csproj @@ -100,7 +100,7 @@ copy Cmd_GZip.exe gunzip.exe - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj index 4f6bb416a..d40eef52e 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_Tar/Cmd_Tar.csproj @@ -91,7 +91,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj index 0e3d31240..311fcb85d 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/Cmd_ZipInfo/Cmd_ZipInfo.csproj @@ -99,7 +99,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj index 61dcf0166..efd2cd464 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/CreateZipFile/CreateZipFile.csproj @@ -107,7 +107,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj index 6a948c6b5..efacf9ff8 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/FastZip/FastZip.csproj @@ -90,7 +90,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj index fa3f6b8fc..43403d1e4 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/unzipfile/unzipfile.csproj @@ -61,7 +61,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj index 0b10efd15..4734de832 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/cs/viewzipfile/viewzipfile.csproj @@ -61,7 +61,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj index 2057acd9f..42db45963 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/CreateZipFile/CreateZipFile.vbproj @@ -95,7 +95,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj index e6ccebddc..d86ec9e00 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/WpfCreateZipFile/WpfCreateZipFile.vbproj @@ -171,7 +171,7 @@ - 1.3.1 + 1.3.3 1.0.2 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj index 429d77bfc..c85b1082e 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/viewzipfile/viewzipfile.vbproj @@ -90,7 +90,7 @@ - 1.3.1 + 1.3.3 diff --git a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj index ddde8318d..b8b02293e 100644 --- a/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj +++ b/samples/ICSharpCode.SharpZipLib.Samples/vb/zipfiletest/zipfiletest.vbproj @@ -100,7 +100,7 @@ - 1.3.1 + 1.3.3 From 05372be6268a3f95789174860e57a8bb615d8d44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Fri, 18 Feb 2022 10:44:30 +0100 Subject: [PATCH 138/162] ci: use server 2019 for win builds --- .github/workflows/build-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index b6b0eeb2a..9cffe4b67 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -117,7 +117,7 @@ jobs: Pack: needs: [Build, Test, CodeCov] - runs-on: windows-latest + runs-on: windows-2019 env: PKG_SUFFIX: '' PKG_PROJ: src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj From 71fe846be1f405ab1d9833510ef6d24339bd77ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Fri, 18 Feb 2022 11:25:23 +0100 Subject: [PATCH 139/162] ci: use server 2019 for win builds (#727) --- .github/workflows/build-test.yml | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 9cffe4b67..d5630331f 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -14,14 +14,14 @@ on: jobs: Build: - runs-on: ${{ matrix.os }}-latest + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: - os: [ubuntu, windows, macos] + os: [ubuntu-latest, windows-2019, macos-latest] target: [netstandard2.0, netstandard2.1] include: - - os: windows + - os: windows-2019 target: net45 env: LIB_PROJ: src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -35,6 +35,9 @@ jobs: uses: actions/setup-dotnet@v1 with: dotnet-version: '3.1.x' + + - name: Show .NET info + run: dotnet --info - name: Build library (Debug) run: dotnet build -c debug -f ${{ matrix.target }} ${{ env.LIB_PROJ }} @@ -73,7 +76,7 @@ jobs: CodeCov: name: Code Coverage - runs-on: windows-latest + runs-on: windows-2019 env: DOTCOVER_VER: 2021.1.2 DOTCOVER_PKG: jetbrains.dotcover.commandlinetools From cc8dd78ed989888f6685da4cc009c529158738b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Wed, 23 Mar 2022 13:44:02 +0100 Subject: [PATCH 140/162] fix(zip): dont fail test on 0 sizes and descriptor (#736) --- .../Zip/ZipConstants.cs | 24 ++++++++++++++ src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 32 +++++++++---------- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs index 6d4892d55..204196d85 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs @@ -472,4 +472,28 @@ public static class ZipConstants #endregion Header Signatures } + + /// + /// GeneralBitFlags helper extensions + /// + public static class GenericBitFlagsExtensions + { + /// + /// Efficiently check if any of the flags are set without enum un-/boxing + /// + /// + /// + /// Returns whether any of flags are set + public static bool HasAny(this GeneralBitFlags target, GeneralBitFlags flags) + => ((int)target & (int)flags) != 0; + + /// + /// Efficiently check if all the flags are set without enum un-/boxing + /// + /// + /// + /// Returns whether the flags are all set + public static bool HasAll(this GeneralBitFlags target, GeneralBitFlags flags) + => ((int)target & (int)flags) == (int)flags; + } } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 0a844916e..1e9bf43d3 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1115,7 +1115,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } var extractVersion = (short)(ReadLEUshort() & 0x00ff); - var localFlags = (short)ReadLEUshort(); + var localFlags = (GeneralBitFlags)ReadLEUshort(); var compressionMethod = (short)ReadLEUshort(); var fileTime = (short)ReadLEUshort(); var fileDate = (short)ReadLEUshort(); @@ -1142,15 +1142,15 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) size = localExtraData.ReadLong(); compressedSize = localExtraData.ReadLong(); - if ((localFlags & (int)GeneralBitFlags.Descriptor) != 0) + if (localFlags.HasAny(GeneralBitFlags.Descriptor)) { // These may be valid if patched later - if ((size != -1) && (size != entry.Size)) + if ((size > 0) && (size != entry.Size)) { throw new ZipException("Size invalid for descriptor"); } - if ((compressedSize != -1) && (compressedSize != entry.CompressedSize)) + if ((compressedSize > 0) && (compressedSize != entry.CompressedSize)) { throw new ZipException("Compressed size invalid for descriptor"); } @@ -1181,7 +1181,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) throw new ZipException(string.Format("Version required to extract this entry not supported ({0})", extractVersion)); } - if ((localFlags & (int)(GeneralBitFlags.Patched | GeneralBitFlags.StrongEncryption | GeneralBitFlags.EnhancedCompress | GeneralBitFlags.HeaderMasked)) != 0) + if (localFlags.HasAny(GeneralBitFlags.Patched | GeneralBitFlags.StrongEncryption | GeneralBitFlags.EnhancedCompress | GeneralBitFlags.HeaderMasked)) { throw new ZipException("The library does not support the zip version required to extract this entry"); } @@ -1213,21 +1213,21 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) var localEncoding = _stringCodec.ZipInputEncoding(localFlags); // Local entry flags dont have reserved bit set on. - if ((localFlags & (int)(GeneralBitFlags.ReservedPKware4 | GeneralBitFlags.ReservedPkware14 | GeneralBitFlags.ReservedPkware15)) != 0) + if (localFlags.HasAny(GeneralBitFlags.ReservedPKware4 | GeneralBitFlags.ReservedPkware14 | GeneralBitFlags.ReservedPkware15)) { throw new ZipException("Reserved bit flags cannot be set."); } // Encryption requires extract version >= 20 - if (((localFlags & (int)GeneralBitFlags.Encrypted) != 0) && (extractVersion < 20)) + if (localFlags.HasAny(GeneralBitFlags.Encrypted) && extractVersion < 20) { throw new ZipException(string.Format("Version required to extract this entry is too low for encryption ({0})", extractVersion)); } // Strong encryption requires encryption flag to be set and extract version >= 50. - if ((localFlags & (int)GeneralBitFlags.StrongEncryption) != 0) + if (localFlags.HasAny(GeneralBitFlags.StrongEncryption)) { - if ((localFlags & (int)GeneralBitFlags.Encrypted) == 0) + if (!localFlags.HasAny(GeneralBitFlags.Encrypted)) { throw new ZipException("Strong encryption flag set but encryption flag is not set"); } @@ -1239,13 +1239,13 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } // Patched entries require extract version >= 27 - if (((localFlags & (int)GeneralBitFlags.Patched) != 0) && (extractVersion < 27)) + if (localFlags.HasAny(GeneralBitFlags.Patched) && extractVersion < 27) { throw new ZipException(string.Format("Patched data requires higher version than ({0})", extractVersion)); } // Central header flags match local entry flags. - if (localFlags != entry.Flags) + if ((int)localFlags != entry.Flags) { throw new ZipException("Central header/local header flags mismatch"); } @@ -1262,7 +1262,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } // Strong encryption and extract version match - if ((localFlags & (int)GeneralBitFlags.StrongEncryption) != 0) + if (localFlags.HasAny(GeneralBitFlags.StrongEncryption)) { if (extractVersion < 62) { @@ -1270,7 +1270,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } } - if ((localFlags & (int)GeneralBitFlags.HeaderMasked) != 0) + if (localFlags.HasAny(GeneralBitFlags.HeaderMasked)) { if ((fileTime != 0) || (fileDate != 0)) { @@ -1278,7 +1278,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } } - if ((localFlags & (int)GeneralBitFlags.Descriptor) == 0) + if (!localFlags.HasAny(GeneralBitFlags.Descriptor)) { if (crcValue != (uint)entry.Crc) { @@ -1348,7 +1348,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) // Size can be verified only if it is known in the local header. // it will always be known in the central header. - if (((localFlags & (int)GeneralBitFlags.Descriptor) == 0) || + if (!localFlags.HasAny(GeneralBitFlags.Descriptor) || ((size > 0 || compressedSize > 0) && entry.Size > 0)) { if ((size != 0) @@ -2507,7 +2507,7 @@ private void CopyBytes(ZipUpdate update, Stream destination, Stream source, /// The descriptor size, zero if there isn't one. private static int GetDescriptorSize(ZipUpdate update, bool includingSignature) { - if (!((GeneralBitFlags)update.Entry.Flags).HasFlag(GeneralBitFlags.Descriptor)) + if (!((GeneralBitFlags)update.Entry.Flags).HasAny(GeneralBitFlags.Descriptor)) return 0; var descriptorWithSignature = update.Entry.LocalHeaderRequiresZip64 From aee3b44735a008abab276d6ec6a4688353910f09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Wed, 27 Apr 2022 10:33:11 +0200 Subject: [PATCH 141/162] add openupm package badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a27570f45..5f09f1f01 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# SharpZipLib [![Build Status](https://github.com/icsharpcode/SharpZipLib/actions/workflows/build-test.yml/badge.svg?branch=master)](https://github.com/icsharpcode/SharpZipLib/actions/workflows/build-test.yml) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) +# SharpZipLib [![Build Status](https://github.com/icsharpcode/SharpZipLib/actions/workflows/build-test.yml/badge.svg?branch=master)](https://github.com/icsharpcode/SharpZipLib/actions/workflows/build-test.yml) [![NuGet Version](https://img.shields.io/nuget/v/SharpZipLib.svg)](https://www.nuget.org/packages/SharpZipLib/) [![openupm](https://img.shields.io/npm/v/org.icsharpcode.sharpziplib?label=openupm®istry_uri=https://package.openupm.com)](https://openupm.com/packages/org.icsharpcode.sharpziplib/) Introduction ------------ From e3bb2f3bf66de6b8fd25b08c54187388459582b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 28 Apr 2022 14:13:14 +0200 Subject: [PATCH 142/162] feat(zip): make it possible to skip header tests (#689) --- .../Zip/ZipConstants.cs | 15 ++ src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 153 +++++++++--------- .../TestSupport/Utils.cs | 1 - .../TestSupport/ZipTesting.cs | 111 +++++++++---- .../Zip/FastZipHandling.cs | 65 ++++---- .../Zip/GeneralHandling.cs | 23 +-- .../Zip/PassthroughTests.cs | 3 +- .../Zip/StreamHandling.cs | 11 +- .../Zip/ZipEncryptionHandling.cs | 3 +- .../Zip/ZipFileHandling.cs | 94 ++++++----- 10 files changed, 277 insertions(+), 202 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs index 204196d85..b16fdefdf 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs @@ -231,6 +231,21 @@ public enum GeneralBitFlags ///
ReservedPkware15 = 0x8000 } + + /// + /// Helpers for + /// + public static class GeneralBitFlagsExtensions + { + /// + /// This is equivalent of in .NET Core, but since the .NET FW + /// version is really slow (due to un-/boxing and reflection) we use this wrapper. + /// + /// + /// + /// + public static bool Includes(this GeneralBitFlags flagData, GeneralBitFlags flag) => (flag & flagData) != 0; + } #endregion Enumerations diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index 1e9bf43d3..b141f4d8d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1084,6 +1084,7 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl [Flags] private enum HeaderTest { + None = 0x0, Extract = 0x01, // Check that this header represents an entry whose data can be extracted Header = 0x02, // Check that this header contents are valid } @@ -1110,13 +1111,12 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) if (signature != ZipConstants.LocalHeaderSignature) { - throw new ZipException(string.Format("Wrong local header signature at 0x{0:x}, expected 0x{1:x8}, actual 0x{2:x8}", - entryAbsOffset, ZipConstants.LocalHeaderSignature, signature)); + throw new ZipException($"Wrong local header signature at 0x{entryAbsOffset:x}, expected 0x{ZipConstants.LocalHeaderSignature:x8}, actual 0x{signature:x8}"); } var extractVersion = (short)(ReadLEUshort() & 0x00ff); var localFlags = (GeneralBitFlags)ReadLEUshort(); - var compressionMethod = (short)ReadLEUshort(); + var compressionMethod = (CompressionMethod)ReadLEUshort(); var fileTime = (short)ReadLEUshort(); var fileDate = (short)ReadLEUshort(); uint crcValue = ReadLEUint(); @@ -1134,7 +1134,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) var localExtraData = new ZipExtraData(extraData); // Extra data / zip64 checks - if (localExtraData.Find(1)) + if (localExtraData.Find(headerID: 1)) { // 2010-03-04 Forum 10512: removed checks for version >= ZipConstants.VersionZip64 // and size or compressedSize = MaxValue, due to rogue creators. @@ -1175,15 +1175,19 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) throw new ZipException("Compression method not supported"); } - if ((extractVersion > ZipConstants.VersionMadeBy) - || ((extractVersion > 20) && (extractVersion < ZipConstants.VersionZip64))) + if (extractVersion > ZipConstants.VersionMadeBy + || (extractVersion > 20 && extractVersion < ZipConstants.VersionZip64)) { - throw new ZipException(string.Format("Version required to extract this entry not supported ({0})", extractVersion)); + throw new ZipException($"Version required to extract this entry not supported ({extractVersion})"); } - if (localFlags.HasAny(GeneralBitFlags.Patched | GeneralBitFlags.StrongEncryption | GeneralBitFlags.EnhancedCompress | GeneralBitFlags.HeaderMasked)) + const GeneralBitFlags notSupportedFlags = GeneralBitFlags.Patched + | GeneralBitFlags.StrongEncryption + | GeneralBitFlags.EnhancedCompress + | GeneralBitFlags.HeaderMasked; + if (localFlags.HasAny(notSupportedFlags)) { - throw new ZipException("The library does not support the zip version required to extract this entry"); + throw new ZipException($"The library does not support the zip features required to extract this entry ({localFlags & notSupportedFlags:F})"); } } } @@ -1207,7 +1211,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) (extractVersion != 63) ) { - throw new ZipException(string.Format("Version required to extract this entry is invalid ({0})", extractVersion)); + throw new ZipException($"Version required to extract this entry is invalid ({extractVersion})"); } var localEncoding = _stringCodec.ZipInputEncoding(localFlags); @@ -1221,7 +1225,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) // Encryption requires extract version >= 20 if (localFlags.HasAny(GeneralBitFlags.Encrypted) && extractVersion < 20) { - throw new ZipException(string.Format("Version required to extract this entry is too low for encryption ({0})", extractVersion)); + throw new ZipException($"Version required to extract this entry is too low for encryption ({extractVersion})"); } // Strong encryption requires encryption flag to be set and extract version >= 50. @@ -1234,26 +1238,26 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) if (extractVersion < 50) { - throw new ZipException(string.Format("Version required to extract this entry is too low for encryption ({0})", extractVersion)); + throw new ZipException($"Version required to extract this entry is too low for encryption ({extractVersion})"); } } // Patched entries require extract version >= 27 if (localFlags.HasAny(GeneralBitFlags.Patched) && extractVersion < 27) { - throw new ZipException(string.Format("Patched data requires higher version than ({0})", extractVersion)); + throw new ZipException($"Patched data requires higher version than ({extractVersion})"); } // Central header flags match local entry flags. if ((int)localFlags != entry.Flags) { - throw new ZipException("Central header/local header flags mismatch"); + throw new ZipException($"Central header/local header flags mismatch ({(GeneralBitFlags)entry.Flags:F} vs {localFlags:F})"); } // Central header compression method matches local entry - if (entry.CompressionMethodForHeader != (CompressionMethod)compressionMethod) + if (entry.CompressionMethodForHeader != compressionMethod) { - throw new ZipException("Central header/local header compression method mismatch"); + throw new ZipException($"Central header/local header compression method mismatch ({entry.CompressionMethodForHeader:G} vs {compressionMethod:G})"); } if (entry.Version != extractVersion) @@ -1272,7 +1276,7 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) if (localFlags.HasAny(GeneralBitFlags.HeaderMasked)) { - if ((fileTime != 0) || (fileDate != 0)) + if (fileTime != 0 || fileDate != 0) { throw new ZipException("Header masked set but date/time values non-zero"); } @@ -1287,8 +1291,8 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) } // Crc valid for empty entry. - // This will also apply to streamed entries where size isnt known and the header cant be patched - if ((size == 0) && (compressedSize == 0)) + // This will also apply to streamed entries where size isn't known and the header cant be patched + if (size == 0 && compressedSize == 0) { if (crcValue != 0) { @@ -1351,20 +1355,15 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) if (!localFlags.HasAny(GeneralBitFlags.Descriptor) || ((size > 0 || compressedSize > 0) && entry.Size > 0)) { - if ((size != 0) - && (size != entry.Size)) + if (size != 0 && size != entry.Size) { - throw new ZipException( - string.Format("Size mismatch between central header({0}) and local header({1})", - entry.Size, size)); + throw new ZipException($"Size mismatch between central header ({entry.Size}) and local header ({size})"); } - if ((compressedSize != 0) + if (compressedSize != 0 && (compressedSize != entry.CompressedSize && compressedSize != 0xFFFFFFFF && compressedSize != -1)) { - throw new ZipException( - string.Format("Compressed size mismatch between central header({0}) and local header({1})", - entry.CompressedSize, compressedSize)); + throw new ZipException($"Compressed size mismatch between central header({entry.CompressedSize}) and local header({compressedSize})"); } } @@ -3502,20 +3501,16 @@ private void ReadEntries() } bool isZip64 = false; - bool requireZip64 = false; - + // Check if zip64 header information is required. - if ((thisDiskNumber == 0xffff) || - (startCentralDirDisk == 0xffff) || - (entriesForThisDisk == 0xffff) || - (entriesForWholeCentralDir == 0xffff) || - (centralDirSize == 0xffffffff) || - (offsetOfCentralDir == 0xffffffff)) - { - requireZip64 = true; - } - - // #357 - always check for the existance of the Zip64 central directory. + bool requireZip64 = thisDiskNumber == 0xffff || + startCentralDirDisk == 0xffff || + entriesForThisDisk == 0xffff || + entriesForWholeCentralDir == 0xffff || + centralDirSize == 0xffffffff || + offsetOfCentralDir == 0xffffffff; + + // #357 - always check for the existence of the Zip64 central directory. // #403 - Take account of the fixed size of the locator when searching. // Subtract from locatedEndOfCentralDir so that the endLocation is the location of EndOfCentralDirectorySignature, // rather than the data following the signature. @@ -3549,7 +3544,7 @@ private void ReadEntries() if (sig64 != ZipConstants.Zip64CentralFileHeaderSignature) { - throw new ZipException(string.Format("Invalid Zip64 Central directory signature at {0:X}", offset64)); + throw new ZipException($"Invalid Zip64 Central directory signature at {offset64:X}"); } // NOTE: Record size = SizeOfFixedFields + SizeOfVariableData - 12. @@ -3604,8 +3599,11 @@ private void ReadEntries() int extraLen = ReadLEUshort(); int commentLen = ReadLEUshort(); - int diskStartNo = ReadLEUshort(); // Not currently used - int internalAttributes = ReadLEUshort(); // Not currently used + + // ReSharper disable once UnusedVariable, Currently unused but needs to be read to offset the stream + int diskStartNo = ReadLEUshort(); + // ReSharper disable once UnusedVariable, Currently unused but needs to be read to offset the stream + int internalAttributes = ReadLEUshort(); uint externalAttributes = ReadLEUint(); long offset = ReadLEUint(); @@ -3629,7 +3627,7 @@ private void ReadEntries() ExternalFileAttributes = (int)externalAttributes }; - if ((bitFlags & 8) == 0) + if (!entry.HasFlag(GeneralBitFlags.Descriptor)) { entry.CryptoCheckValue = (byte)(crc >> 24); } @@ -3672,9 +3670,15 @@ private void ReadEntries() /// private long LocateEntry(ZipEntry entry) { - return TestLocalHeader(entry, HeaderTest.Extract); + return TestLocalHeader(entry, SkipLocalEntryTestsOnLocate ? HeaderTest.None : HeaderTest.Extract); } + /// + /// Skip the verification of the local header when reading an archive entry. Set this to attempt to read the + /// entries even if the headers should indicate that doing so would fail or produce an unexpected output. + /// + public bool SkipLocalEntryTestsOnLocate { get; set; } = false; + private Stream CreateAndInitDecryptionStream(Stream baseStream, ZipEntry entry) { CryptoStream result = null; @@ -3691,15 +3695,15 @@ private Stream CreateAndInitDecryptionStream(Stream baseStream, ZipEntry entry) } int saltLen = entry.AESSaltLen; byte[] saltBytes = new byte[saltLen]; - int saltIn = StreamUtils.ReadRequestedBytes(baseStream, saltBytes, 0, saltLen); - if (saltIn != saltLen) - throw new ZipException("AES Salt expected " + saltLen + " got " + saltIn); - // + int saltIn = StreamUtils.ReadRequestedBytes(baseStream, saltBytes, offset: 0, saltLen); + + if (saltIn != saltLen) throw new ZipException($"AES Salt expected {saltLen} git {saltIn}"); + byte[] pwdVerifyRead = new byte[2]; StreamUtils.ReadFully(baseStream, pwdVerifyRead); int blockSize = entry.AESKeySize / 8; // bits to bytes - var decryptor = new ZipAESTransform(rawPassword_, saltBytes, blockSize, false); + var decryptor = new ZipAESTransform(rawPassword_, saltBytes, blockSize, writeMode: false); byte[] pwdVerifyCalc = decryptor.PwdVerifier; if (pwdVerifyCalc[0] != pwdVerifyRead[0] || pwdVerifyCalc[1] != pwdVerifyRead[1]) throw new ZipException("Invalid password for AES"); @@ -3712,8 +3716,7 @@ private Stream CreateAndInitDecryptionStream(Stream baseStream, ZipEntry entry) } else { - if ((entry.Version < ZipConstants.VersionStrongEncryption) - || (entry.Flags & (int)GeneralBitFlags.StrongEncryption) == 0) + if (entry.Version < ZipConstants.VersionStrongEncryption || !entry.HasFlag(GeneralBitFlags.StrongEncryption)) { var classicManaged = new PkzipClassicManaged(); @@ -3738,31 +3741,29 @@ private Stream CreateAndInitDecryptionStream(Stream baseStream, ZipEntry entry) private Stream CreateAndInitEncryptionStream(Stream baseStream, ZipEntry entry) { - CryptoStream result = null; - if ((entry.Version < ZipConstants.VersionStrongEncryption) - || (entry.Flags & (int)GeneralBitFlags.StrongEncryption) == 0) - { - var classicManaged = new PkzipClassicManaged(); + if (entry.Version >= ZipConstants.VersionStrongEncryption && + entry.HasFlag(GeneralBitFlags.StrongEncryption)) return null; - OnKeysRequired(entry.Name); - if (HaveKeys == false) - { - throw new ZipException("No password available for encrypted stream"); - } + var classicManaged = new PkzipClassicManaged(); - // Closing a CryptoStream will close the base stream as well so wrap it in an UncompressedStream - // which doesnt do this. - result = new CryptoStream(new UncompressedStream(baseStream), - classicManaged.CreateEncryptor(key, null), CryptoStreamMode.Write); + OnKeysRequired(entry.Name); + if (HaveKeys == false) + { + throw new ZipException("No password available for encrypted stream"); + } - if ((entry.Crc < 0) || (entry.Flags & 8) != 0) - { - WriteEncryptionHeader(result, entry.DosTime << 16); - } - else - { - WriteEncryptionHeader(result, entry.Crc); - } + // Closing a CryptoStream will close the base stream as well so wrap it in an UncompressedStream + // which doesnt do this. + var result = new CryptoStream(new UncompressedStream(baseStream), + classicManaged.CreateEncryptor(key, null), CryptoStreamMode.Write); + + if (entry.Crc < 0 || entry.HasFlag(GeneralBitFlags.Descriptor)) + { + WriteEncryptionHeader(result, entry.DosTime << 16); + } + else + { + WriteEncryptionHeader(result, entry.Crc); } return result; } @@ -3785,7 +3786,7 @@ private static void WriteEncryptionHeader(Stream stream, long crcValue) rng.GetBytes(cryptBuffer); } cryptBuffer[11] = (byte)(crcValue >> 24); - stream.Write(cryptBuffer, 0, cryptBuffer.Length); + stream.Write(cryptBuffer, offset: 0, cryptBuffer.Length); } #endregion Internal routines diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs index d0d2f2175..3c5788b8a 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs @@ -2,7 +2,6 @@ using System; using System.IO; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.TestSupport diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs index fcc4fe9b8..7311da7a2 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/ZipTesting.cs @@ -1,7 +1,9 @@ -using System; using ICSharpCode.SharpZipLib.Zip; -using System.IO; +using NUnit.Framework.Constraints; using NUnit.Framework; +using System.Collections.Generic; +using System.IO; +using System.Linq; namespace ICSharpCode.SharpZipLib.Tests.TestSupport { @@ -12,7 +14,13 @@ internal static class ZipTesting { public static void AssertValidZip(Stream stream, string password = null, bool usesAes = true) { - Assert.That(TestArchive(stream, password), "Archive did not pass ZipFile.TestArchive"); + using var zipFile = new ZipFile(stream) + { + IsStreamOwner = false, + Password = password, + }; + + Assert.That(zipFile, Does.PassTestArchive()); if (!string.IsNullOrEmpty(password) && usesAes) { @@ -30,37 +38,86 @@ public static void AssertValidZip(Stream stream, string password = null, bool us } }, "Archive could not be read by ZipInputStream"); } + } + + public class TestArchiveReport + { + internal const string PassingArchive = "Passing Archive"; + + readonly List _messages = new List(); + public void HandleTestResults(TestStatus status, string message) + { + if (string.IsNullOrWhiteSpace(message)) return; + _messages.Add(message); + } - /// - /// Tests the archive. - /// - /// The data. - /// The password. - /// - public static bool TestArchive(byte[] data, string password = null) + public override string ToString() => _messages.Any() ? string.Join(", ", _messages) : PassingArchive; + } + + public class PassesTestArchiveConstraint : Constraint + { + private readonly string _password; + private readonly bool _testData; + + public PassesTestArchiveConstraint(string password = null, bool testData = true) { - using var ms = new MemoryStream(data); - return TestArchive(new MemoryStream(data), password); + _password = password; + _testData = testData; } - /// - /// Tests the archive. - /// - /// The data. - /// The password. - /// true if archive tests ok; false otherwise. - public static bool TestArchive(Stream stream, string password = null) + public override string Description => TestArchiveReport.PassingArchive; + + public override ConstraintResult ApplyTo(TActual actual) { - using var zipFile = new ZipFile(stream) + MemoryStream ms = null; + try { - IsStreamOwner = false, - Password = password, - }; - - return zipFile.TestArchive(true, TestStrategy.FindAllErrors, (status, message) => + if (!(actual is ZipFile zipFile)) + { + if (!(actual is byte[] rawArchive)) + { + return new ConstraintResult(this, actual, ConstraintStatus.Failure); + } + + ms = new MemoryStream(rawArchive); + zipFile = new ZipFile(ms){Password = _password}; + } + + var report = new TestArchiveReport(); + + return new ConstraintResult( + this, report, zipFile.TestArchive( + _testData, + TestStrategy.FindAllErrors, + report.HandleTestResults + ) + ? ConstraintStatus.Success + : ConstraintStatus.Failure); + } + finally { - if (!string.IsNullOrWhiteSpace(message)) TestContext.Out.WriteLine(message); - }); + ms?.Dispose(); + } } } + + public static class ZipTestingConstraintExtensions + { + public static IResolveConstraint PassTestArchive(this ConstraintExpression expression, string password = null, bool testData = true) + { + var constraint = new PassesTestArchiveConstraint(password, testData); + expression.Append(constraint); + return constraint; + } + } + + /// + public class Does: NUnit.Framework.Does + { + public static IResolveConstraint PassTestArchive(string password = null, bool testData = true) + => new PassesTestArchiveConstraint(password, testData); + + public static IResolveConstraint PassTestArchive(bool testData) + => new PassesTestArchiveConstraint(password: null, testData); + } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs index 90b5784ff..3858f38f8 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/FastZipHandling.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Text; +using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; using TimeSetting = ICSharpCode.SharpZipLib.Zip.ZipEntryFactory.TimeSetting; namespace ICSharpCode.SharpZipLib.Tests.Zip @@ -40,7 +41,7 @@ public void Basics() ZipEntry entry = zf[0]; Assert.AreEqual(tempName1, entry.Name); Assert.AreEqual(1, entry.Size); - Assert.IsTrue(zf.TestArchive(true)); + Assert.That(zf, Does.PassTestArchive()); zf.Close(); } @@ -128,7 +129,7 @@ public void CreateEmptyDirectories(string password) var folderEntry = zipFile.GetEntry("floyd/"); Assert.That(folderEntry.IsDirectory, Is.True, "The entry must be a folder"); - Assert.IsTrue(zipFile.TestArchive(testData: true)); + Assert.That(zipFile, Does.PassTestArchive()); } } } @@ -166,6 +167,7 @@ public void ContentEqualAfterAfterArchived([Values(0, 1, 64)]int contentSize) public void Encryption(ZipEncryptionMethod encryptionMethod) { const string tempName1 = "a.dat"; + const int tempSize = 1; var target = new MemoryStream(); @@ -173,7 +175,7 @@ public void Encryption(ZipEncryptionMethod encryptionMethod) Assert.IsNotNull(tempFilePath, "No permission to execute this test?"); string addFile = Path.Combine(tempFilePath, tempName1); - MakeTempFile(addFile, 1); + MakeTempFile(addFile, tempSize); try { @@ -189,17 +191,13 @@ public void Encryption(ZipEncryptionMethod encryptionMethod) using (ZipFile zf = new ZipFile(archive)) { zf.Password = "Ahoy"; - Assert.AreEqual(1, zf.Count); - ZipEntry entry = zf[0]; - Assert.AreEqual(tempName1, entry.Name); - Assert.AreEqual(1, entry.Size); - Assert.IsTrue(zf.TestArchive(true, TestStrategy.FindFirstError, (status, message) => - { - if(!string.IsNullOrEmpty(message)) { - Console.WriteLine($"{message} ({status.Entry?.Name ?? "-"})"); - } - })); - Assert.IsTrue(entry.IsCrypted); + Assert.That(zf.Count, Is.EqualTo(1)); + var entry = zf[0]; + Assert.That(entry.Name, Is.EqualTo(tempName1)); + Assert.That(entry.Size, Is.EqualTo(tempSize)); + Assert.That(entry.IsCrypted); + + Assert.That(zf, Does.PassTestArchive()); switch (encryptionMethod) { @@ -363,6 +361,7 @@ public void ExtractExceptions() public void ReadingOfLockedDataFiles() { const string tempName1 = "a.dat"; + const int tempSize = 1; var target = new MemoryStream(); @@ -370,7 +369,7 @@ public void ReadingOfLockedDataFiles() Assert.IsNotNull(tempFilePath, "No permission to execute this test?"); string addFile = Path.Combine(tempFilePath, tempName1); - MakeTempFile(addFile, 1); + MakeTempFile(addFile, tempSize); try { @@ -383,11 +382,11 @@ public void ReadingOfLockedDataFiles() var archive = new MemoryStream(target.ToArray()); using (ZipFile zf = new ZipFile(archive)) { - Assert.AreEqual(1, zf.Count); - ZipEntry entry = zf[0]; - Assert.AreEqual(tempName1, entry.Name); - Assert.AreEqual(1, entry.Size); - Assert.IsTrue(zf.TestArchive(true)); + Assert.That(zf.Count, Is.EqualTo(1)); + var entry = zf[0]; + Assert.That(entry.Name, Is.EqualTo(tempName1)); + Assert.That(entry.Size, Is.EqualTo(tempSize)); + Assert.That(zf, Does.PassTestArchive()); zf.Close(); } @@ -404,6 +403,7 @@ public void ReadingOfLockedDataFiles() public void NonAsciiPasswords() { const string tempName1 = "a.dat"; + const int tempSize = 1; var target = new MemoryStream(); @@ -411,7 +411,7 @@ public void NonAsciiPasswords() Assert.IsNotNull(tempFilePath, "No permission to execute this test?"); string addFile = Path.Combine(tempFilePath, tempName1); - MakeTempFile(addFile, 1); + MakeTempFile(addFile, tempSize); string password = "abc\u0066\u0393"; try @@ -425,12 +425,12 @@ public void NonAsciiPasswords() using (ZipFile zf = new ZipFile(archive)) { zf.Password = password; - Assert.AreEqual(1, zf.Count); - ZipEntry entry = zf[0]; - Assert.AreEqual(tempName1, entry.Name); - Assert.AreEqual(1, entry.Size); - Assert.IsTrue(zf.TestArchive(true)); - Assert.IsTrue(entry.IsCrypted); + Assert.That(zf.Count, Is.EqualTo(1)); + var entry = zf[0]; + Assert.That(entry.Name, Is.EqualTo(tempName1)); + Assert.That(entry.Size, Is.EqualTo(tempSize)); + Assert.That(zf, Does.PassTestArchive()); + Assert.That(entry.IsCrypted); } } finally @@ -636,10 +636,11 @@ public void SetDirectoryModifiedDate() public void CreateZipShouldLeaveOutputStreamOpenIfRequested(bool leaveOpen) { const string tempFileName = "a(2).dat"; + const int tempSize = 16; using var tempFolder = Utils.GetTempDir(); // Create test input file - tempFolder.CreateDummyFile(tempFileName, size: 16); + tempFolder.CreateDummyFile(tempFileName, tempSize); // Create the zip with fast zip var target = new TrackedMemoryStream(); @@ -653,11 +654,11 @@ public void CreateZipShouldLeaveOutputStreamOpenIfRequested(bool leaveOpen) // Check that the file contents are correct in both cases var archive = new MemoryStream(target.ToArray()); using var zf = new ZipFile(archive); - Assert.AreEqual(expected: 1, zf.Count); + Assert.That(zf.Count, Is.EqualTo(1)); var entry = zf[0]; - Assert.AreEqual(tempFileName, entry.Name); - Assert.AreEqual(expected: 16, entry.Size); - Assert.IsTrue(zf.TestArchive(testData: true)); + Assert.That(entry.Name, Is.EqualTo(tempFileName)); + Assert.That(entry.Size, Is.EqualTo(tempSize)); + Assert.That(zf, Does.PassTestArchive()); } [Category("Zip")] diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs index e16a82967..d45eedf3c 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/GeneralHandling.cs @@ -9,6 +9,7 @@ using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Text; +using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -383,7 +384,7 @@ public void StoredNonSeekableKnownSizeNoCrc() index += count; } } - Assert.IsTrue(ZipTesting.TestArchive(ms.ToArray())); + Assert.That(ms.ToArray(), Does.PassTestArchive()); } [Test] @@ -391,20 +392,20 @@ public void StoredNonSeekableKnownSizeNoCrc() public void StoredNonSeekableKnownSizeNoCrcEncrypted() { // This cant be stored directly as the crc is not known - const int TargetSize = 24692; - const string Password = "Mabutu"; + const int targetSize = 24692; + const string password = "Mabutu"; MemoryStream ms = new MemoryStreamWithoutSeek(); using (ZipOutputStream outStream = new ZipOutputStream(ms)) { - outStream.Password = Password; + outStream.Password = password; outStream.IsStreamOwner = false; var entry = new ZipEntry("dummyfile.tst"); entry.CompressionMethod = CompressionMethod.Stored; // The bit thats in question is setting the size before its added to the archive. - entry.Size = TargetSize; + entry.Size = targetSize; outStream.PutNextEntry(entry); @@ -413,7 +414,7 @@ public void StoredNonSeekableKnownSizeNoCrcEncrypted() var rnd = new Random(); - int size = TargetSize; + int size = targetSize; byte[] original = new byte[size]; rnd.NextBytes(original); @@ -429,7 +430,7 @@ public void StoredNonSeekableKnownSizeNoCrcEncrypted() index += count; } } - Assert.IsTrue(ZipTesting.TestArchive(ms.ToArray(), Password)); + Assert.That(ms.ToArray(), Does.PassTestArchive(password)); } /// @@ -502,10 +503,10 @@ public void MixedEncryptedAndPlain() int extractCount = 0; int extractIndex = 0; - ZipEntry entry; + byte[] decompressedData = new byte[100]; - while ((entry = inStream.GetNextEntry()) != null) + while (inStream.GetNextEntry() != null) { extractCount = decompressedData.Length; extractIndex = 0; @@ -531,7 +532,7 @@ public void MixedEncryptedAndPlain() [Category("Zip")] public void BasicStoredEncrypted() { - ExerciseZip(CompressionMethod.Stored, 0, 50000, "Rosebud", true); + ExerciseZip(CompressionMethod.Stored, compressionLevel: 0, size: 50000, "Rosebud", canSeek: true); } /// @@ -542,7 +543,7 @@ public void BasicStoredEncrypted() [Category("Zip")] public void BasicStoredEncryptedNonSeekable() { - ExerciseZip(CompressionMethod.Stored, 0, 50000, "Rosebud", false); + ExerciseZip(CompressionMethod.Stored, compressionLevel: 0, size: 50000, "Rosebud", canSeek: false); } /// diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs index 1a4b266f2..954e339b1 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/PassthroughTests.cs @@ -6,6 +6,7 @@ using ICSharpCode.SharpZipLib.Tests.TestSupport; using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; +using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -34,7 +35,7 @@ public void AddingValidPrecompressedEntryToZipOutputStream() compressedData.CopyTo(outStream); } - Assert.IsTrue(ZipTesting.TestArchive(ms.ToArray())); + Assert.That(ms.ToArray(), Does.PassTestArchive()); } private static (MemoryStream, Crc32, int) CreateDeflatedData() diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index 3e8b9a9ee..2f1e866fd 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -4,6 +4,7 @@ using NUnit.Framework; using System; using System.IO; +using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -77,7 +78,7 @@ public void Zip64Descriptor() outStream.WriteByte(89); outStream.Close(); - Assert.IsTrue(ZipTesting.TestArchive(msw.ToArray())); + Assert.That(msw.ToArray(), Does.PassTestArchive()); msw = new MemoryStreamWithoutSeek(); outStream = new ZipOutputStream(msw); @@ -88,7 +89,7 @@ public void Zip64Descriptor() outStream.WriteByte(89); outStream.Close(); - Assert.IsTrue(ZipTesting.TestArchive(msw.ToArray())); + Assert.That(msw.ToArray(), Does.PassTestArchive()); } [Test] @@ -110,7 +111,7 @@ public void ReadAndWriteZip64NonSeekable() outStream.Close(); } - Assert.IsTrue(ZipTesting.TestArchive(msw.ToArray())); + Assert.That(msw.ToArray(), Does.PassTestArchive()); msw.Position = 0; @@ -147,7 +148,7 @@ public void EntryWithNoDataAndZip64() outStream.Finish(); outStream.Close(); - Assert.IsTrue(ZipTesting.TestArchive(msw.ToArray())); + Assert.That(msw.ToArray(), Does.PassTestArchive()); } /// @@ -273,7 +274,7 @@ public void WriteZipStreamWithNoCompression([Values(0, 1, 256)] int contentLengt Assert.AreEqual(inputBytes, outputBytes, "Archive content does not match the source content"); }, "Failed to locate entry stream in archive"); - Assert.IsTrue(zf.TestArchive(testData: true), "Archive did not pass TestArchive"); + Assert.That(zf, Does.PassTestArchive()); } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index f3a240d30..0cf7395cb 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -5,6 +5,7 @@ using System.Text; using ICSharpCode.SharpZipLib.Tests.TestSupport; using System.Threading.Tasks; +using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -105,7 +106,7 @@ public void ZipFileAesDecryption() } } - Assert.That(zipFile.TestArchive(false), Is.True, "Encrypted archive should pass validation."); + Assert.That(zipFile, Does.PassTestArchive(testData: false), "Encrypted archive should pass validation."); } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs index 2d641370c..e594cd17f 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipFileHandling.cs @@ -6,6 +6,7 @@ using System.IO; using System.Text; using System.Threading.Tasks; +using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; namespace ICSharpCode.SharpZipLib.Tests.Zip { @@ -61,7 +62,7 @@ public void Zip64Entries() } zipFile.CommitUpdate(); - Assert.IsTrue(zipFile.TestArchive(true)); + Assert.That(zipFile, Does.PassTestArchive()); Assert.AreEqual(target, zipFile.Count, "Incorrect number of entries stored"); } } @@ -80,7 +81,7 @@ public void EmbeddedArchive() f.Add(m, "a.dat"); f.Add(m, "b.dat"); f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); } byte[] rawArchive = memStream.ToArray(); @@ -116,7 +117,7 @@ public void Zip64Useage() f.Add(m, "a.dat"); f.Add(m, "b.dat"); f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); } byte[] rawArchive = memStream.ToArray(); @@ -211,7 +212,7 @@ public void FakeZip64Locator() f.BeginUpdate(new MemoryArchiveStorage()); f.Add(m, "a.dat", CompressionMethod.Stored); f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); } memStream.Seek(0, SeekOrigin.Begin); @@ -367,7 +368,7 @@ private void TryDeleting(byte[] master, int totalEntries, int additions, params { f.IsStreamOwner = false; Assert.AreEqual(totalEntries, f.Count); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); f.BeginUpdate(new MemoryArchiveStorage()); for (int i = 0; i < additions; ++i) @@ -401,7 +402,7 @@ private void TryDeleting(byte[] master, int totalEntries, int additions, params { f.IsStreamOwner = false; Assert.AreEqual(totalEntries, f.Count); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); f.BeginUpdate(new MemoryArchiveStorage()); for (int i = 0; i < additions; ++i) @@ -445,7 +446,7 @@ public void AddAndDeleteEntriesMemory() f.Add(new StringMemoryDataSource("Mr C"), @"c\c.dat"); f.Add(new StringMemoryDataSource("Mrs D was a star"), @"d\d.dat"); f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); foreach (ZipEntry entry in f) { Console.WriteLine($" - {entry.Name}"); @@ -506,27 +507,27 @@ public void AddAndDeleteEntries() f.Add(addFile2); f.AddDirectory(addDirectory); f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); } using (ZipFile f = new ZipFile(tempFile)) { Assert.AreEqual(3, f.Count); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); // Delete file f.BeginUpdate(); f.Delete(f[0]); f.CommitUpdate(); Assert.AreEqual(2, f.Count); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); // Delete directory f.BeginUpdate(); f.Delete(f[1]); f.CommitUpdate(); Assert.AreEqual(1, f.Count); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); } File.Delete(addFile); @@ -632,7 +633,7 @@ public void AddToEmptyArchive() f.Add(addFile); f.CommitUpdate(); Assert.AreEqual(1, f.Count); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); } using (ZipFile f = new ZipFile(tempFile)) @@ -642,7 +643,7 @@ public void AddToEmptyArchive() f.Delete(f[0]); f.CommitUpdate(); Assert.AreEqual(0, f.Count); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); f.Close(); } @@ -667,7 +668,7 @@ public void CreateEmptyArchive() { f.BeginUpdate(); f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); f.Close(); } @@ -692,7 +693,7 @@ public void CreateArchiveWithNoCompression() zf.BeginUpdate(); zf.Add(sourceFile, CompressionMethod.Stored); zf.CommitUpdate(); - Assert.IsTrue(zf.TestArchive(testData: true)); + Assert.That(zf, Does.PassTestArchive()); zf.Close(); } @@ -864,7 +865,7 @@ public void ArchiveTesting() using (ZipFile testFile = new ZipFile(ms)) { - Assert.IsTrue(testFile.TestArchive(true), "Unexpected error in archive detected"); + Assert.That(testFile, Does.PassTestArchive(), "Unexpected error in archive detected"); byte[] corrupted = new byte[compressedData.Length]; Array.Copy(compressedData, corrupted, compressedData.Length); @@ -875,7 +876,7 @@ public void ArchiveTesting() using (ZipFile testFile = new ZipFile(ms)) { - Assert.IsFalse(testFile.TestArchive(true), "Error in archive not detected"); + Assert.That(testFile, Does.Not.PassTestArchive(), "Error in archive not detected"); } } @@ -889,7 +890,7 @@ private void TestDirectoryEntry(MemoryStream s) var ms2 = new MemoryStream(s.ToArray()); using (ZipFile zf = new ZipFile(ms2)) { - Assert.IsTrue(zf.TestArchive(true)); + Assert.That(zf, Does.PassTestArchive()); } } @@ -913,10 +914,7 @@ private void TestEncryptedDirectoryEntry(MemoryStream s, int aesKeySize) var ms2 = new MemoryStream(s.ToArray()); using (ZipFile zf = new ZipFile(ms2)) { - Assert.IsTrue(zf.TestArchive(true, TestStrategy.FindAllErrors, - (status, message) => { - if (!string.IsNullOrWhiteSpace(message)) TestContext.Out.WriteLine(message); - })); + Assert.That(zf, Does.PassTestArchive()); } } @@ -945,7 +943,7 @@ public void Crypto_AddEncryptedEntryToExistingArchiveSafe() testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); rawData = ms.ToArray(); } @@ -953,14 +951,14 @@ public void Crypto_AddEncryptedEntryToExistingArchiveSafe() using (ZipFile testFile = new ZipFile(ms)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); testFile.BeginUpdate(new MemoryArchiveStorage(FileUpdateMode.Safe)); testFile.Password = "pwd"; testFile.Add(new StringMemoryDataSource("Zapata!"), "encrypttest.xml"); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); int entryIndex = testFile.FindEntry("encrypttest.xml", true); Assert.IsNotNull(entryIndex >= 0); @@ -983,12 +981,12 @@ public void Crypto_AddEncryptedEntryToExistingArchiveDirect() testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); } using (ZipFile testFile = new ZipFile(ms)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); testFile.IsStreamOwner = true; testFile.BeginUpdate(); @@ -996,7 +994,7 @@ public void Crypto_AddEncryptedEntryToExistingArchiveDirect() testFile.Add(new StringMemoryDataSource("Zapata!"), "encrypttest.xml"); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); int entryIndex = testFile.FindEntry("encrypttest.xml", true); Assert.IsNotNull(entryIndex >= 0); @@ -1022,7 +1020,7 @@ public void UnicodeNames() } f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(testData: true)); + Assert.That(f, Does.PassTestArchive()); } memStream.Seek(0, SeekOrigin.Begin); using (var zf = new ZipFile(memStream)) @@ -1062,12 +1060,12 @@ public void UpdateCommentOnlyInMemory() testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); } using (ZipFile testFile = new ZipFile(ms)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); Assert.AreEqual("", testFile.ZipFileComment); testFile.IsStreamOwner = false; @@ -1075,12 +1073,12 @@ public void UpdateCommentOnlyInMemory() testFile.SetComment("Here is my comment"); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); } using (ZipFile testFile = new ZipFile(ms)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); Assert.AreEqual("Here is my comment", testFile.ZipFileComment); } } @@ -1107,24 +1105,24 @@ public void UpdateCommentOnlyOnDisk() testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); } using (ZipFile testFile = new ZipFile(tempFile)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); Assert.AreEqual("", testFile.ZipFileComment); testFile.BeginUpdate(new DiskArchiveStorage(testFile, FileUpdateMode.Direct)); testFile.SetComment("Here is my comment"); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); } using (ZipFile testFile = new ZipFile(tempFile)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); Assert.AreEqual("Here is my comment", testFile.ZipFileComment); } File.Delete(tempFile); @@ -1138,24 +1136,24 @@ public void UpdateCommentOnlyOnDisk() testFile.Add(new StringMemoryDataSource("No3"), "No3", CompressionMethod.Stored); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); } using (ZipFile testFile = new ZipFile(tempFile)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); Assert.AreEqual("", testFile.ZipFileComment); testFile.BeginUpdate(); testFile.SetComment("Here is my comment"); testFile.CommitUpdate(); - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); } using (ZipFile testFile = new ZipFile(tempFile)) { - Assert.IsTrue(testFile.TestArchive(true)); + Assert.That(testFile, Does.PassTestArchive()); Assert.AreEqual("Here is my comment", testFile.ZipFileComment); } File.Delete(tempFile); @@ -1188,7 +1186,7 @@ public void NameFactory() CompressionMethod.Deflated, true); } f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); foreach (string name in names) { @@ -1238,7 +1236,7 @@ public void NestedArchive() using (ZipFile nested = new ZipFile(zipFile.GetInputStream(0))) { - Assert.IsTrue(nested.TestArchive(true)); + Assert.That(nested, Does.PassTestArchive()); Assert.AreEqual(1, nested.Count); Stream nestedStream = nested.GetInputStream(0); @@ -1628,7 +1626,7 @@ public void ZipWithBZip2Compression(bool encryptEntries) var m2 = new StringMemoryDataSource("DeflateCompressed"); f.Add(m2, "b.dat", CompressionMethod.Deflated); f.CommitUpdate(); - Assert.IsTrue(f.TestArchive(true)); + Assert.That(f, Does.PassTestArchive()); } memStream.Seek(0, SeekOrigin.Begin); @@ -1757,7 +1755,7 @@ public void TestDescriptorUpdateOnDelete(UseZip64 useZip64) } var zipData = msw.ToArray(); - Assert.IsTrue(ZipTesting.TestArchive(zipData)); + Assert.That(zipData, Does.PassTestArchive()); using (var memoryStream = new MemoryStream(zipData)) { @@ -1772,7 +1770,7 @@ public void TestDescriptorUpdateOnDelete(UseZip64 useZip64) using (var zipFile = new ZipFile(memoryStream, leaveOpen: true)) { - Assert.That(zipFile.TestArchive(true), Is.True); + Assert.That(zipFile, Does.PassTestArchive()); } } } @@ -1796,7 +1794,7 @@ public void TestDescriptorUpdateOnAdd(UseZip64 useZip64) } var zipData = msw.ToArray(); - Assert.IsTrue(ZipTesting.TestArchive(zipData)); + Assert.That(zipData, Does.PassTestArchive()); using (var memoryStream = new MemoryStream()) { @@ -1813,7 +1811,7 @@ public void TestDescriptorUpdateOnAdd(UseZip64 useZip64) using (var zipFile = new ZipFile(memoryStream, leaveOpen: true)) { - Assert.That(zipFile.TestArchive(true), Is.True); + Assert.That(zipFile, Does.PassTestArchive()); } } } From e589b5e84b27e2d9efc47a11e105a0cd117c8c32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 28 Apr 2022 14:20:35 +0200 Subject: [PATCH 143/162] fix(zip): 0 in zip64 local sizes using descriptors (#750) --- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 4 ++-- src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index b141f4d8d..ce216dacc 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -1145,12 +1145,12 @@ private long TestLocalHeader(ZipEntry entry, HeaderTest tests) if (localFlags.HasAny(GeneralBitFlags.Descriptor)) { // These may be valid if patched later - if ((size > 0) && (size != entry.Size)) + if ((size != 0) && (size != entry.Size)) { throw new ZipException("Size invalid for descriptor"); } - if ((compressedSize > 0) && (compressedSize != entry.CompressedSize)) + if ((compressedSize != 0) && (compressedSize != entry.CompressedSize)) { throw new ZipException("Compressed size invalid for descriptor"); } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs index a37ab3031..cf78ef54f 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFormat.cs @@ -114,8 +114,9 @@ internal static int WriteLocalHeader(Stream stream, ZipEntry entry, out EntryPat } else { - ed.AddLeLong(-1); - ed.AddLeLong(-1); + // If the sizes are stored in the descriptor, the local Zip64 sizes should be 0 + ed.AddLeLong(0); + ed.AddLeLong(0); } ed.AddNewEntry(1); From d843d6db4767f2f36c8607df4a293ae6e2add9d7 Mon Sep 17 00:00:00 2001 From: Nathan Date: Tue, 24 May 2022 10:39:40 +0100 Subject: [PATCH 144/162] feat(tar): support for async streams (#746) --- .../Program.cs | 4 +- .../Tar/TarInputStream.cs | 82 ++++ .../Tar/TarOutputStream.cs | 64 +++ .../Core/ExactMemoryPool.cs | 71 ++++ .../Core/StringBuilderPool.cs | 22 ++ .../ICSharpCode.SharpZipLib.csproj | 14 +- src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs | 189 ++++++--- src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs | 96 +---- src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs | 252 ++++++------ .../Tar/TarInputStream.cs | 370 ++++++++++++------ .../Tar/TarOutputStream.cs | 187 ++++++--- .../Core/StringBuilderPoolTests.cs | 77 ++++ .../Tar/TarBufferTests.cs | 125 ++++++ .../Tar/TarInputStreamTests.cs | 91 +++++ .../Tar/TarTests.cs | 13 +- 15 files changed, 1239 insertions(+), 418 deletions(-) create mode 100644 benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarInputStream.cs create mode 100644 benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarOutputStream.cs create mode 100644 src/ICSharpCode.SharpZipLib/Core/ExactMemoryPool.cs create mode 100644 src/ICSharpCode.SharpZipLib/Core/StringBuilderPool.cs create mode 100644 test/ICSharpCode.SharpZipLib.Tests/Core/StringBuilderPoolTests.cs create mode 100644 test/ICSharpCode.SharpZipLib.Tests/Tar/TarBufferTests.cs create mode 100644 test/ICSharpCode.SharpZipLib.Tests/Tar/TarInputStreamTests.cs diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs index 9c79e6551..697e2923a 100644 --- a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Program.cs @@ -1,6 +1,4 @@ -using System; -using BenchmarkDotNet; -using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Configs; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Running; using BenchmarkDotNet.Toolchains.CsProj; diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarInputStream.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarInputStream.cs new file mode 100644 index 000000000..b59a217ab --- /dev/null +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarInputStream.cs @@ -0,0 +1,82 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BenchmarkDotNet.Attributes; +using ICSharpCode.SharpZipLib.Tar; + +namespace ICSharpCode.SharpZipLib.Benchmark.Tar +{ + [MemoryDiagnoser] + [Config(typeof(MultipleRuntimes))] + public class TarInputStream + { + private readonly byte[] archivedData; + private readonly byte[] readBuffer = new byte[1024]; + + public TarInputStream() + { + using (var outputMemoryStream = new MemoryStream()) + { + using (var zipOutputStream = + new ICSharpCode.SharpZipLib.Tar.TarOutputStream(outputMemoryStream, Encoding.UTF8)) + { + var tarEntry = TarEntry.CreateTarEntry("some file"); + tarEntry.Size = 1024 * 1024; + zipOutputStream.PutNextEntry(tarEntry); + + var rng = RandomNumberGenerator.Create(); + var inputBuffer = new byte[1024]; + rng.GetBytes(inputBuffer); + + for (int i = 0; i < 1024; i++) + { + zipOutputStream.Write(inputBuffer, 0, inputBuffer.Length); + } + } + + archivedData = outputMemoryStream.ToArray(); + } + } + + [Benchmark] + public long ReadTarInputStream() + { + using (var memoryStream = new MemoryStream(archivedData)) + using (var zipInputStream = new ICSharpCode.SharpZipLib.Tar.TarInputStream(memoryStream, Encoding.UTF8)) + { + var entry = zipInputStream.GetNextEntry(); + + while (zipInputStream.Read(readBuffer, 0, readBuffer.Length) > 0) + { + } + + return entry.Size; + } + } + + [Benchmark] + public async Task ReadTarInputStreamAsync() + { + using (var memoryStream = new MemoryStream(archivedData)) + using (var zipInputStream = new ICSharpCode.SharpZipLib.Tar.TarInputStream(memoryStream, Encoding.UTF8)) + { + var entry = await zipInputStream.GetNextEntryAsync(CancellationToken.None); + +#if NETCOREAPP2_1_OR_GREATER + while (await zipInputStream.ReadAsync(readBuffer.AsMemory()) > 0) + { + } +#else + while (await zipInputStream.ReadAsync(readBuffer, 0, readBuffer.Length) > 0) + { + } +#endif + + return entry.Size; + } + } + } +} diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarOutputStream.cs b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarOutputStream.cs new file mode 100644 index 000000000..f24e83e35 --- /dev/null +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/Tar/TarOutputStream.cs @@ -0,0 +1,64 @@ +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using BenchmarkDotNet.Attributes; +using ICSharpCode.SharpZipLib.Tar; + +namespace ICSharpCode.SharpZipLib.Benchmark.Tar +{ + [MemoryDiagnoser] + [Config(typeof(MultipleRuntimes))] + public class TarOutputStream + { + private readonly byte[] backingArray = new byte[1024 * 1024 + (6 * 1024)]; + private readonly byte[] inputBuffer = new byte[1024]; + private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create(); + + [Benchmark] + public void WriteTarOutputStream() + { + using (var outputMemoryStream = new MemoryStream(backingArray)) + { + using (var tarOutputStream = + new ICSharpCode.SharpZipLib.Tar.TarOutputStream(outputMemoryStream, Encoding.UTF8)) + { + var tarEntry = TarEntry.CreateTarEntry("some file"); + tarEntry.Size = 1024 * 1024; + tarOutputStream.PutNextEntry(tarEntry); + + _rng.GetBytes(inputBuffer); + + for (int i = 0; i < 1024; i++) + { + tarOutputStream.Write(inputBuffer, 0, inputBuffer.Length); + } + } + } + } + + [Benchmark] + public async Task WriteTarOutputStreamAsync() + { + using (var outputMemoryStream = new MemoryStream(backingArray)) + { + using (var tarOutputStream = + new ICSharpCode.SharpZipLib.Tar.TarOutputStream(outputMemoryStream, Encoding.UTF8)) + { + var tarEntry = TarEntry.CreateTarEntry("some file"); + tarEntry.Size = 1024 * 1024; + + await tarOutputStream.PutNextEntryAsync(tarEntry, CancellationToken.None); + + _rng.GetBytes(inputBuffer); + + for (int i = 0; i < 1024; i++) + { + await tarOutputStream.WriteAsync(inputBuffer, 0, inputBuffer.Length); + } + } + } + } + } +} diff --git a/src/ICSharpCode.SharpZipLib/Core/ExactMemoryPool.cs b/src/ICSharpCode.SharpZipLib/Core/ExactMemoryPool.cs new file mode 100644 index 000000000..d03ca2ecf --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Core/ExactMemoryPool.cs @@ -0,0 +1,71 @@ +using System; +using System.Buffers; + +namespace ICSharpCode.SharpZipLib.Core +{ + /// + /// A MemoryPool that will return a Memory which is exactly the length asked for using the bufferSize parameter. + /// This is in contrast to the default ArrayMemoryPool which will return a Memory of equal size to the underlying + /// array which at least as long as the minBufferSize parameter. + /// Note: The underlying array may be larger than the slice of Memory + /// + /// + internal sealed class ExactMemoryPool : MemoryPool + { + public new static readonly MemoryPool Shared = new ExactMemoryPool(); + + public override IMemoryOwner Rent(int bufferSize = -1) + { + if ((uint)bufferSize > int.MaxValue || bufferSize < 0) + { + throw new ArgumentOutOfRangeException(nameof(bufferSize)); + } + + return new ExactMemoryPoolBuffer(bufferSize); + } + + protected override void Dispose(bool disposing) + { + } + + public override int MaxBufferSize => int.MaxValue; + + private sealed class ExactMemoryPoolBuffer : IMemoryOwner, IDisposable + { + private T[] array; + private readonly int size; + + public ExactMemoryPoolBuffer(int size) + { + this.size = size; + this.array = ArrayPool.Shared.Rent(size); + } + + public Memory Memory + { + get + { + T[] array = this.array; + if (array == null) + { + throw new ObjectDisposedException(nameof(ExactMemoryPoolBuffer)); + } + + return new Memory(array).Slice(0, size); + } + } + + public void Dispose() + { + T[] array = this.array; + if (array == null) + { + return; + } + + this.array = null; + ArrayPool.Shared.Return(array); + } + } + } +} diff --git a/src/ICSharpCode.SharpZipLib/Core/StringBuilderPool.cs b/src/ICSharpCode.SharpZipLib/Core/StringBuilderPool.cs new file mode 100644 index 000000000..a1121f0cc --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Core/StringBuilderPool.cs @@ -0,0 +1,22 @@ +using System.Collections.Concurrent; +using System.Text; + +namespace ICSharpCode.SharpZipLib.Core +{ + internal class StringBuilderPool + { + public static StringBuilderPool Instance { get; } = new StringBuilderPool(); + private readonly ConcurrentQueue pool = new ConcurrentQueue(); + + public StringBuilder Rent() + { + return pool.TryDequeue(out var builder) ? builder : new StringBuilder(); + } + + public void Return(StringBuilder builder) + { + builder.Clear(); + pool.Enqueue(builder); + } + } +} diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index 066c4fb43..e736ad1cc 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -33,8 +33,18 @@ Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.3 for mor - - + + + + + + + + + + + + True images diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs b/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs index 744c13189..b190ed1f3 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarBuffer.cs @@ -1,5 +1,8 @@ using System; +using System.Buffers; using System.IO; +using System.Threading; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tar { @@ -72,10 +75,7 @@ or which contains garbage records after a zero block. /// This is equal to the multiplied by the public int RecordSize { - get - { - return recordSize; - } + get { return recordSize; } } /// @@ -95,10 +95,7 @@ public int GetRecordSize() /// This is the number of blocks in each record. public int BlockFactor { - get - { - return blockFactor; - } + get { return blockFactor; } } /// @@ -207,7 +204,7 @@ private void Initialize(int archiveBlockFactor) { blockFactor = archiveBlockFactor; recordSize = archiveBlockFactor * BlockSize; - recordBuffer = new byte[RecordSize]; + recordBuffer = ArrayPool.Shared.Rent(RecordSize); if (inputStream != null) { @@ -289,7 +286,14 @@ public static bool IsEndOfArchiveBlock(byte[] block) /// /// Skip over a block on the input stream. /// - public void SkipBlock() + public void SkipBlock() => SkipBlockAsync(CancellationToken.None, false).GetAwaiter().GetResult(); + + /// + /// Skip over a block on the input stream. + /// + public Task SkipBlockAsync(CancellationToken ct) => SkipBlockAsync(ct, true).AsTask(); + + private async ValueTask SkipBlockAsync(CancellationToken ct, bool isAsync) { if (inputStream == null) { @@ -298,7 +302,7 @@ public void SkipBlock() if (currentBlockIndex >= BlockFactor) { - if (!ReadRecord()) + if (!await ReadRecordAsync(ct, isAsync)) { throw new TarException("Failed to read a record"); } @@ -322,7 +326,7 @@ public byte[] ReadBlock() if (currentBlockIndex >= BlockFactor) { - if (!ReadRecord()) + if (!ReadRecordAsync(CancellationToken.None, false).GetAwaiter().GetResult()) { throw new TarException("Failed to read a record"); } @@ -335,13 +339,37 @@ public byte[] ReadBlock() return result; } + internal async ValueTask ReadBlockIntAsync(byte[] buffer, CancellationToken ct, bool isAsync) + { + if (buffer.Length != BlockSize) + { + throw new ArgumentException("BUG: buffer must have length BlockSize"); + } + + if (inputStream == null) + { + throw new TarException("TarBuffer.ReadBlock - no input stream defined"); + } + + if (currentBlockIndex >= BlockFactor) + { + if (!await ReadRecordAsync(ct, isAsync)) + { + throw new TarException("Failed to read a record"); + } + } + + recordBuffer.AsSpan().Slice(currentBlockIndex * BlockSize, BlockSize).CopyTo(buffer); + currentBlockIndex++; + } + /// /// Read a record from data stream. /// /// /// false if End-Of-File, else true. /// - private bool ReadRecord() + private async ValueTask ReadRecordAsync(CancellationToken ct, bool isAsync) { if (inputStream == null) { @@ -355,7 +383,9 @@ private bool ReadRecord() while (bytesNeeded > 0) { - long numBytes = inputStream.Read(recordBuffer, offset, bytesNeeded); + long numBytes = isAsync + ? await inputStream.ReadAsync(recordBuffer, offset, bytesNeeded, ct) + : inputStream.Read(recordBuffer, offset, bytesNeeded); // // NOTE @@ -438,6 +468,18 @@ public int GetCurrentRecordNum() return currentRecordIndex; } + /// + /// Write a block of data to the archive. + /// + /// + /// The data to write to the archive. + /// + /// + public ValueTask WriteBlockAsync(byte[] block, CancellationToken ct) + { + return WriteBlockAsync(block, 0, ct); + } + /// /// Write a block of data to the archive. /// @@ -446,30 +488,24 @@ public int GetCurrentRecordNum() /// public void WriteBlock(byte[] block) { - if (block == null) - { - throw new ArgumentNullException(nameof(block)); - } - - if (outputStream == null) - { - throw new TarException("TarBuffer.WriteBlock - no output stream defined"); - } - - if (block.Length != BlockSize) - { - string errorText = string.Format("TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'", - block.Length, BlockSize); - throw new TarException(errorText); - } - - if (currentBlockIndex >= BlockFactor) - { - WriteRecord(); - } + WriteBlock(block, 0); + } - Array.Copy(block, 0, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); - currentBlockIndex++; + /// + /// Write an archive record to the archive, where the record may be + /// inside of a larger array buffer. The buffer must be "offset plus + /// record size" long. + /// + /// + /// The buffer containing the record data to write. + /// + /// + /// The offset of the record data within buffer. + /// + /// + public ValueTask WriteBlockAsync(byte[] buffer, int offset, CancellationToken ct) + { + return WriteBlockAsync(buffer, offset, ct, true); } /// @@ -484,6 +520,11 @@ public void WriteBlock(byte[] block) /// The offset of the record data within buffer. /// public void WriteBlock(byte[] buffer, int offset) + { + WriteBlockAsync(buffer, offset, CancellationToken.None, false).GetAwaiter().GetResult(); + } + + internal async ValueTask WriteBlockAsync(byte[] buffer, int offset, CancellationToken ct, bool isAsync) { if (buffer == null) { @@ -502,14 +543,15 @@ public void WriteBlock(byte[] buffer, int offset) if ((offset + BlockSize) > buffer.Length) { - string errorText = string.Format("TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", + string errorText = string.Format( + "TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", buffer.Length, offset, recordSize); throw new TarException(errorText); } if (currentBlockIndex >= BlockFactor) { - WriteRecord(); + await WriteRecordAsync(CancellationToken.None, isAsync); } Array.Copy(buffer, offset, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); @@ -520,15 +562,23 @@ public void WriteBlock(byte[] buffer, int offset) /// /// Write a TarBuffer record to the archive. /// - private void WriteRecord() + private async ValueTask WriteRecordAsync(CancellationToken ct, bool isAsync) { if (outputStream == null) { throw new TarException("TarBuffer.WriteRecord no output stream defined"); } - outputStream.Write(recordBuffer, 0, RecordSize); - outputStream.Flush(); + if (isAsync) + { + await outputStream.WriteAsync(recordBuffer, 0, RecordSize, ct); + await outputStream.FlushAsync(ct); + } + else + { + outputStream.Write(recordBuffer, 0, RecordSize); + outputStream.Flush(); + } currentBlockIndex = 0; currentRecordIndex++; @@ -539,7 +589,7 @@ private void WriteRecord() /// /// Any trailing bytes are set to zero which is by definition correct behaviour /// for the end of a tar stream. - private void WriteFinalRecord() + private async ValueTask WriteFinalRecordAsync(CancellationToken ct, bool isAsync) { if (outputStream == null) { @@ -550,36 +600,77 @@ private void WriteFinalRecord() { int dataBytes = currentBlockIndex * BlockSize; Array.Clear(recordBuffer, dataBytes, RecordSize - dataBytes); - WriteRecord(); + await WriteRecordAsync(ct, isAsync); } - outputStream.Flush(); + if (isAsync) + { + await outputStream.FlushAsync(ct); + } + else + { + outputStream.Flush(); + } } /// /// Close the TarBuffer. If this is an output buffer, also flush the /// current block before closing. /// - public void Close() + public void Close() => CloseAsync(CancellationToken.None, false).GetAwaiter().GetResult(); + + /// + /// Close the TarBuffer. If this is an output buffer, also flush the + /// current block before closing. + /// + public Task CloseAsync(CancellationToken ct) => CloseAsync(ct, true).AsTask(); + + private async ValueTask CloseAsync(CancellationToken ct, bool isAsync) { if (outputStream != null) { - WriteFinalRecord(); + await WriteFinalRecordAsync(ct, isAsync); if (IsStreamOwner) { - outputStream.Dispose(); + if (isAsync) + { +#if NETSTANDARD2_1_OR_GREATER + await outputStream.DisposeAsync(); +#else + outputStream.Dispose(); +#endif + } + else + { + outputStream.Dispose(); + } } + outputStream = null; } else if (inputStream != null) { if (IsStreamOwner) { - inputStream.Dispose(); + if (isAsync) + { +#if NETSTANDARD2_1_OR_GREATER + await inputStream.DisposeAsync(); +#else + inputStream.Dispose(); +#endif + } + else + { + inputStream.Dispose(); + } } + inputStream = null; } + + ArrayPool.Shared.Return(recordBuffer); } #region Instance Fields diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs index 262c12ad3..2f3cf7862 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs @@ -114,7 +114,8 @@ public object Clone() public static TarEntry CreateTarEntry(string name) { var entry = new TarEntry(); - TarEntry.NameTarHeader(entry.header, name); + + entry.NameTarHeader(name); return entry; } @@ -188,10 +189,7 @@ public bool IsDescendent(TarEntry toTest) /// public TarHeader TarHeader { - get - { - return header; - } + get { return header; } } /// @@ -199,14 +197,8 @@ public TarHeader TarHeader /// public string Name { - get - { - return header.Name; - } - set - { - header.Name = value; - } + get { return header.Name; } + set { header.Name = value; } } /// @@ -214,14 +206,8 @@ public string Name /// public int UserId { - get - { - return header.UserId; - } - set - { - header.UserId = value; - } + get { return header.UserId; } + set { header.UserId = value; } } /// @@ -229,14 +215,8 @@ public int UserId /// public int GroupId { - get - { - return header.GroupId; - } - set - { - header.GroupId = value; - } + get { return header.GroupId; } + set { header.GroupId = value; } } /// @@ -244,14 +224,8 @@ public int GroupId /// public string UserName { - get - { - return header.UserName; - } - set - { - header.UserName = value; - } + get { return header.UserName; } + set { header.UserName = value; } } /// @@ -259,14 +233,8 @@ public string UserName /// public string GroupName { - get - { - return header.GroupName; - } - set - { - header.GroupName = value; - } + get { return header.GroupName; } + set { header.GroupName = value; } } /// @@ -304,14 +272,8 @@ public void SetNames(string userName, string groupName) /// public DateTime ModTime { - get - { - return header.ModTime; - } - set - { - header.ModTime = value; - } + get { return header.ModTime; } + set { header.ModTime = value; } } /// @@ -322,10 +284,7 @@ public DateTime ModTime /// public string File { - get - { - return file; - } + get { return file; } } /// @@ -333,14 +292,8 @@ public string File /// public long Size { - get - { - return header.Size; - } - set - { - header.Size = value; - } + get { return header.Size; } + set { header.Size = value; } } /// @@ -450,7 +403,8 @@ public void GetFileTarHeader(TarHeader header, string file) header.Size = new FileInfo(file.Replace('/', Path.DirectorySeparatorChar)).Length; } - header.ModTime = System.IO.File.GetLastWriteTime(file.Replace('/', Path.DirectorySeparatorChar)).ToUniversalTime(); + header.ModTime = System.IO.File.GetLastWriteTime(file.Replace('/', Path.DirectorySeparatorChar)) + .ToUniversalTime(); header.DevMajor = 0; header.DevMinor = 0; } @@ -543,19 +497,11 @@ static public void AdjustEntryName(byte[] buffer, string newName, Encoding nameE /// /// Fill in a TarHeader given only the entry's name. /// - /// - /// The TarHeader to fill in. - /// /// /// The tar entry name. /// - static public void NameTarHeader(TarHeader header, string name) + public void NameTarHeader(string name) { - if (header == null) - { - throw new ArgumentNullException(nameof(header)); - } - if (name == null) { throw new ArgumentNullException(nameof(name)); diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs b/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs index 3bd1bdffe..36d6eca44 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarHeader.cs @@ -1,5 +1,7 @@ using System; +using System.Buffers; using System.Text; +using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Tar { @@ -124,106 +126,106 @@ public class TarHeader /// /// Normal file type. /// - public const byte LF_NORMAL = (byte)'0'; + public const byte LF_NORMAL = (byte) '0'; /// /// Link file type. /// - public const byte LF_LINK = (byte)'1'; + public const byte LF_LINK = (byte) '1'; /// /// Symbolic link file type. /// - public const byte LF_SYMLINK = (byte)'2'; + public const byte LF_SYMLINK = (byte) '2'; /// /// Character device file type. /// - public const byte LF_CHR = (byte)'3'; + public const byte LF_CHR = (byte) '3'; /// /// Block device file type. /// - public const byte LF_BLK = (byte)'4'; + public const byte LF_BLK = (byte) '4'; /// /// Directory file type. /// - public const byte LF_DIR = (byte)'5'; + public const byte LF_DIR = (byte) '5'; /// /// FIFO (pipe) file type. /// - public const byte LF_FIFO = (byte)'6'; + public const byte LF_FIFO = (byte) '6'; /// /// Contiguous file type. /// - public const byte LF_CONTIG = (byte)'7'; + public const byte LF_CONTIG = (byte) '7'; /// /// Posix.1 2001 global extended header /// - public const byte LF_GHDR = (byte)'g'; + public const byte LF_GHDR = (byte) 'g'; /// /// Posix.1 2001 extended header /// - public const byte LF_XHDR = (byte)'x'; + public const byte LF_XHDR = (byte) 'x'; // POSIX allows for upper case ascii type as extensions /// /// Solaris access control list file type /// - public const byte LF_ACL = (byte)'A'; + public const byte LF_ACL = (byte) 'A'; /// /// GNU dir dump file type /// This is a dir entry that contains the names of files that were in the /// dir at the time the dump was made /// - public const byte LF_GNU_DUMPDIR = (byte)'D'; + public const byte LF_GNU_DUMPDIR = (byte) 'D'; /// /// Solaris Extended Attribute File /// - public const byte LF_EXTATTR = (byte)'E'; + public const byte LF_EXTATTR = (byte) 'E'; /// /// Inode (metadata only) no file content /// - public const byte LF_META = (byte)'I'; + public const byte LF_META = (byte) 'I'; /// /// Identifies the next file on the tape as having a long link name /// - public const byte LF_GNU_LONGLINK = (byte)'K'; + public const byte LF_GNU_LONGLINK = (byte) 'K'; /// /// Identifies the next file on the tape as having a long name /// - public const byte LF_GNU_LONGNAME = (byte)'L'; + public const byte LF_GNU_LONGNAME = (byte) 'L'; /// /// Continuation of a file that began on another volume /// - public const byte LF_GNU_MULTIVOL = (byte)'M'; + public const byte LF_GNU_MULTIVOL = (byte) 'M'; /// /// For storing filenames that dont fit in the main header (old GNU) /// - public const byte LF_GNU_NAMES = (byte)'N'; + public const byte LF_GNU_NAMES = (byte) 'N'; /// /// GNU Sparse file /// - public const byte LF_GNU_SPARSE = (byte)'S'; + public const byte LF_GNU_SPARSE = (byte) 'S'; /// /// GNU Tape/volume header ignore on extraction /// - public const byte LF_GNU_VOLHDR = (byte)'V'; + public const byte LF_GNU_VOLHDR = (byte) 'V'; /// /// The magic tag representing a POSIX tar archive. (would be written with a trailing NULL) @@ -235,7 +237,7 @@ public class TarHeader /// public const string GNU_TMAGIC = "ustar "; - private const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds + private const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds private static readonly DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0); #endregion Constants @@ -277,6 +279,7 @@ public string Name { throw new ArgumentNullException(nameof(value)); } + name = value; } } @@ -339,6 +342,7 @@ public long Size { throw new ArgumentOutOfRangeException(nameof(value), "Cannot be less than zero"); } + size = value; } } @@ -359,6 +363,7 @@ public DateTime ModTime { throw new ArgumentOutOfRangeException(nameof(value), "ModTime cannot be before Jan 1st 1970"); } + modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second); } } @@ -401,6 +406,7 @@ public string LinkName { throw new ArgumentNullException(nameof(value)); } + linkName = value; } } @@ -418,6 +424,7 @@ public string Magic { throw new ArgumentNullException(nameof(value)); } + magic = value; } } @@ -428,10 +435,7 @@ public string Magic /// Thrown when attempting to set Version to null. public string Version { - get - { - return version; - } + get { return version; } set { @@ -439,6 +443,7 @@ public string Version { throw new ArgumentNullException(nameof(value)); } + version = value; } } @@ -462,6 +467,7 @@ public string UserName { currentUser = currentUser.Substring(0, UNAMELEN); } + userName = currentUser; } } @@ -539,17 +545,18 @@ public void ParseBuffer(byte[] header, Encoding nameEncoding) } int offset = 0; + var headerSpan = header.AsSpan(); - name = ParseName(header, offset, NAMELEN, nameEncoding).ToString(); + name = ParseName(headerSpan.Slice(offset, NAMELEN), nameEncoding); offset += NAMELEN; - mode = (int)ParseOctal(header, offset, MODELEN); + mode = (int) ParseOctal(header, offset, MODELEN); offset += MODELEN; - UserId = (int)ParseOctal(header, offset, UIDLEN); + UserId = (int) ParseOctal(header, offset, UIDLEN); offset += UIDLEN; - GroupId = (int)ParseOctal(header, offset, GIDLEN); + GroupId = (int) ParseOctal(header, offset, GIDLEN); offset += GIDLEN; Size = ParseBinaryOrOctal(header, offset, SIZELEN); @@ -558,35 +565,35 @@ public void ParseBuffer(byte[] header, Encoding nameEncoding) ModTime = GetDateTimeFromCTime(ParseOctal(header, offset, MODTIMELEN)); offset += MODTIMELEN; - checksum = (int)ParseOctal(header, offset, CHKSUMLEN); + checksum = (int) ParseOctal(header, offset, CHKSUMLEN); offset += CHKSUMLEN; TypeFlag = header[offset++]; - LinkName = ParseName(header, offset, NAMELEN, nameEncoding).ToString(); + LinkName = ParseName(headerSpan.Slice(offset, NAMELEN), nameEncoding); offset += NAMELEN; - Magic = ParseName(header, offset, MAGICLEN, nameEncoding).ToString(); + Magic = ParseName(headerSpan.Slice(offset, MAGICLEN), nameEncoding); offset += MAGICLEN; if (Magic == "ustar") { - Version = ParseName(header, offset, VERSIONLEN, nameEncoding).ToString(); + Version = ParseName(headerSpan.Slice(offset, VERSIONLEN), nameEncoding); offset += VERSIONLEN; - UserName = ParseName(header, offset, UNAMELEN, nameEncoding).ToString(); + UserName = ParseName(headerSpan.Slice(offset, UNAMELEN), nameEncoding); offset += UNAMELEN; - GroupName = ParseName(header, offset, GNAMELEN, nameEncoding).ToString(); + GroupName = ParseName(headerSpan.Slice(offset, GNAMELEN), nameEncoding); offset += GNAMELEN; - DevMajor = (int)ParseOctal(header, offset, DEVLEN); + DevMajor = (int) ParseOctal(header, offset, DEVLEN); offset += DEVLEN; - DevMinor = (int)ParseOctal(header, offset, DEVLEN); + DevMinor = (int) ParseOctal(header, offset, DEVLEN); offset += DEVLEN; - string prefix = ParseName(header, offset, PREFIXLEN, nameEncoding).ToString(); + string prefix = ParseName(headerSpan.Slice(offset, PREFIXLEN), nameEncoding); if (!string.IsNullOrEmpty(prefix)) Name = prefix + '/' + Name; } @@ -640,7 +647,7 @@ public void WriteHeader(byte[] outBuffer, Encoding nameEncoding) int csOffset = offset; for (int c = 0; c < CHKSUMLEN; ++c) { - outBuffer[offset++] = (byte)' '; + outBuffer[offset++] = (byte) ' '; } outBuffer[offset++] = TypeFlag; @@ -690,25 +697,26 @@ public override bool Equals(object obj) if (localHeader != null) { result = (name == localHeader.name) - && (mode == localHeader.mode) - && (UserId == localHeader.UserId) - && (GroupId == localHeader.GroupId) - && (Size == localHeader.Size) - && (ModTime == localHeader.ModTime) - && (Checksum == localHeader.Checksum) - && (TypeFlag == localHeader.TypeFlag) - && (LinkName == localHeader.LinkName) - && (Magic == localHeader.Magic) - && (Version == localHeader.Version) - && (UserName == localHeader.UserName) - && (GroupName == localHeader.GroupName) - && (DevMajor == localHeader.DevMajor) - && (DevMinor == localHeader.DevMinor); + && (mode == localHeader.mode) + && (UserId == localHeader.UserId) + && (GroupId == localHeader.GroupId) + && (Size == localHeader.Size) + && (ModTime == localHeader.ModTime) + && (Checksum == localHeader.Checksum) + && (TypeFlag == localHeader.TypeFlag) + && (LinkName == localHeader.LinkName) + && (Magic == localHeader.Magic) + && (Version == localHeader.Version) + && (UserName == localHeader.UserName) + && (GroupName == localHeader.GroupName) + && (DevMajor == localHeader.DevMajor) + && (DevMinor == localHeader.DevMinor); } else { result = false; } + return result; } @@ -719,7 +727,7 @@ public override bool Equals(object obj) /// Value to apply as a default for userName. /// Value to apply as a default for groupId. /// Value to apply as a default for groupName. - static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName) + internal static void SetValueDefaults(int userId, string userName, int groupId, string groupName) { defaultUserId = userIdAsSet = userId; defaultUser = userNameAsSet = userName; @@ -727,7 +735,7 @@ static internal void SetValueDefaults(int userId, string userName, int groupId, defaultGroupName = groupNameAsSet = groupName; } - static internal void RestoreSetValues() + internal static void RestoreSetValues() { defaultUserId = userIdAsSet; defaultUser = userNameAsSet; @@ -737,7 +745,7 @@ static internal void RestoreSetValues() // Return value that may be stored in octal or binary. Length must exceed 8. // - static private long ParseBinaryOrOctal(byte[] header, int offset, int length) + private static long ParseBinaryOrOctal(byte[] header, int offset, int length) { if (header[offset] >= 0x80) { @@ -747,8 +755,10 @@ static private long ParseBinaryOrOctal(byte[] header, int offset, int length) { result = result << 8 | header[offset + pos]; } + return result; } + return ParseOctal(header, offset, length); } @@ -759,7 +769,7 @@ static private long ParseBinaryOrOctal(byte[] header, int offset, int length) /// The offset into the buffer from which to parse. /// The number of header bytes to parse. /// The long equivalent of the octal string. - static public long ParseOctal(byte[] header, int offset, int length) + public static long ParseOctal(byte[] header, int offset, int length) { if (header == null) { @@ -777,14 +787,14 @@ static public long ParseOctal(byte[] header, int offset, int length) break; } - if (header[i] == (byte)' ' || header[i] == '0') + if (header[i] == (byte) ' ' || header[i] == '0') { if (stillPadding) { continue; } - if (header[i] == (byte)' ') + if (header[i] == (byte) ' ') { break; } @@ -814,9 +824,9 @@ static public long ParseOctal(byte[] header, int offset, int length) /// The name parsed. /// [Obsolete("No Encoding for Name field is specified, any non-ASCII bytes will be discarded")] - static public StringBuilder ParseName(byte[] header, int offset, int length) + public static string ParseName(byte[] header, int offset, int length) { - return ParseName(header, offset, length, null); + return ParseName(header.AsSpan().Slice(offset, length), null); } /// @@ -825,66 +835,50 @@ static public StringBuilder ParseName(byte[] header, int offset, int length) /// /// The header buffer from which to parse. /// - /// - /// The offset into the buffer from which to parse. - /// - /// - /// The number of header bytes to parse. - /// /// /// name encoding, or null for ASCII only /// /// /// The name parsed. /// - static public StringBuilder ParseName(byte[] header, int offset, int length, Encoding encoding) + public static string ParseName(ReadOnlySpan header, Encoding encoding) { - if (header == null) - { - throw new ArgumentNullException(nameof(header)); - } - - if (offset < 0) - { - throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be less than zero"); - } - - if (length < 0) - { - throw new ArgumentOutOfRangeException(nameof(length), "Cannot be less than zero"); - } - - if (offset + length > header.Length) - { - throw new ArgumentException("Exceeds header size", nameof(length)); - } - - var result = new StringBuilder(length); + var builder = StringBuilderPool.Instance.Rent(); int count = 0; - if(encoding == null) + if (encoding == null) { - for (int i = offset; i < offset + length; ++i) + for (int i = 0; i < header.Length; ++i) { - if (header[i] == 0) + var b = header[i]; + if (b == 0) { break; } - result.Append((char)header[i]); + + builder.Append((char) b); } } else { - for(int i = offset; i < offset + length; ++i, ++count) + for (int i = 0; i < header.Length; ++i, ++count) { - if(header[i] == 0) + if (header[i] == 0) { break; } } - result.Append(encoding.GetString(header, offset, count)); + +#if NETSTANDARD2_1_OR_GREATER + var value = encoding.GetString(header.Slice(0, count)); +#else + var value = encoding.GetString(header.ToArray(), 0, count); +#endif + builder.Append(value); } + var result = builder.ToString(); + StringBuilderPool.Instance.Return(builder); return result; } @@ -926,7 +920,8 @@ public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int b /// The number of characters/bytes to add /// name encoding, or null for ASCII only /// The next free index in the - public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length, Encoding encoding) + public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length, + Encoding encoding) { if (name == null) { @@ -939,20 +934,24 @@ public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int b } int i; - if(encoding != null) + if (encoding != null) { // it can be more sufficient if using Span or unsafe - var nameArray = name.ToCharArray(nameOffset, Math.Min(name.Length - nameOffset, length)); + ReadOnlySpan nameArray = + name.AsSpan().Slice(nameOffset, Math.Min(name.Length - nameOffset, length)); + var charArray = ArrayPool.Shared.Rent(nameArray.Length); + nameArray.CopyTo(charArray); + // it can be more sufficient if using Span(or unsafe?) and ArrayPool for temporary buffer - var bytes = encoding.GetBytes(nameArray, 0, nameArray.Length); - i = Math.Min(bytes.Length, length); - Array.Copy(bytes, 0, buffer, bufferOffset, i); + var bytesLength = encoding.GetBytes(charArray, 0, nameArray.Length, buffer, bufferOffset); + ArrayPool.Shared.Return(charArray); + i = Math.Min(bytesLength, length); } else { for (i = 0; i < length && nameOffset + i < name.Length; ++i) { - buffer[bufferOffset + i] = (byte)name[nameOffset + i]; + buffer[bufferOffset + i] = (byte) name[nameOffset + i]; } } @@ -960,8 +959,10 @@ public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int b { buffer[bufferOffset + i] = 0; } + return bufferOffset + length; } + /// /// Add an entry name to the buffer /// @@ -1060,6 +1061,7 @@ public static int GetNameBytes(string name, byte[] buffer, int offset, int lengt return GetNameBytes(name, 0, buffer, offset, length, encoding); } + /// /// Add a string to a buffer as a collection of ascii bytes. /// @@ -1085,7 +1087,8 @@ public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int /// The number of ascii characters to add. /// String encoding, or null for ASCII only /// The next free index in the buffer. - public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length, Encoding encoding) + public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length, + Encoding encoding) { if (toAdd == null) { @@ -1098,11 +1101,11 @@ public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int } int i; - if(encoding == null) + if (encoding == null) { for (i = 0; i < length && nameOffset + i < toAdd.Length; ++i) { - buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i]; + buffer[bufferOffset + i] = (byte) toAdd[nameOffset + i]; } } else @@ -1114,6 +1117,7 @@ public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int i = Math.Min(bytes.Length, length); Array.Copy(bytes, 0, buffer, bufferOffset, i); } + // If length is beyond the toAdd string length (which is OK by the prev loop condition), eg if a field has fixed length and the string is shorter, make sure all of the extra chars are written as NULLs, so that the reader func would ignore them and get back the original string for (; i < length; ++i) buffer[bufferOffset + i] = 0; @@ -1155,14 +1159,14 @@ public static int GetOctalBytes(long value, byte[] buffer, int offset, int lengt { for (long v = value; (localIndex >= 0) && (v > 0); --localIndex) { - buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7)); + buffer[offset + localIndex] = (byte) ((byte) '0' + (byte) (v & 7)); v >>= 3; } } for (; localIndex >= 0; --localIndex) { - buffer[offset + localIndex] = (byte)'0'; + buffer[offset + localIndex] = (byte) '0'; } return offset + length; @@ -1179,16 +1183,19 @@ public static int GetOctalBytes(long value, byte[] buffer, int offset, int lengt private static int GetBinaryOrOctalBytes(long value, byte[] buffer, int offset, int length) { if (value > 0x1FFFFFFFF) - { // Octal 77777777777 (11 digits) - // Put value as binary, right-justified into the buffer. Set high order bit of left-most byte. + { + // Octal 77777777777 (11 digits) + // Put value as binary, right-justified into the buffer. Set high order bit of left-most byte. for (int pos = length - 1; pos > 0; pos--) { - buffer[offset + pos] = (byte)value; + buffer[offset + pos] = (byte) value; value = value >> 8; } + buffer[offset] = 0x80; return offset + length; } + return GetOctalBytes(value, buffer, offset, length); } @@ -1222,6 +1229,7 @@ private static int ComputeCheckSum(byte[] buffer) { sum += buffer[i]; } + return sum; } @@ -1240,19 +1248,20 @@ private static int MakeCheckSum(byte[] buffer) for (int i = 0; i < CHKSUMLEN; ++i) { - sum += (byte)' '; + sum += (byte) ' '; } for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i) { sum += buffer[i]; } + return sum; } private static int GetCTime(DateTime dateTime) { - return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor)); + return unchecked((int) ((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor)); } private static DateTime GetDateTimeFromCTime(long ticks) @@ -1267,6 +1276,7 @@ private static DateTime GetDateTimeFromCTime(long ticks) { result = dateTime1970; } + return result; } @@ -1294,16 +1304,16 @@ private static DateTime GetDateTimeFromCTime(long ticks) #region Class Fields // Values used during recursive operations. - static internal int userIdAsSet; + internal static int userIdAsSet; - static internal int groupIdAsSet; - static internal string userNameAsSet; - static internal string groupNameAsSet = "None"; + internal static int groupIdAsSet; + internal static string userNameAsSet; + internal static string groupNameAsSet = "None"; - static internal int defaultUserId; - static internal int defaultGroupId; - static internal string defaultGroupName = "None"; - static internal string defaultUser; + internal static int defaultUserId; + internal static int defaultGroupId; + internal static string defaultGroupName = "None"; + internal static string defaultUser; #endregion Class Fields } diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs b/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs index f1a3622de..36e294628 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarInputStream.cs @@ -1,6 +1,10 @@ using System; +using System.Buffers; using System.IO; using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Tar { @@ -23,6 +27,7 @@ public TarInputStream(Stream inputStream) : this(inputStream, TarBuffer.DefaultBlockFactor, null) { } + /// /// Construct a TarInputStream with default block factor /// @@ -79,10 +84,7 @@ public bool IsStreamOwner /// public override bool CanRead { - get - { - return inputStream.CanRead; - } + get { return inputStream.CanRead; } } /// @@ -91,10 +93,7 @@ public override bool CanRead /// public override bool CanSeek { - get - { - return false; - } + get { return false; } } /// @@ -103,10 +102,7 @@ public override bool CanSeek /// public override bool CanWrite { - get - { - return false; - } + get { return false; } } /// @@ -114,10 +110,7 @@ public override bool CanWrite /// public override long Length { - get - { - return inputStream.Length; - } + get { return inputStream.Length; } } /// @@ -127,14 +120,8 @@ public override long Length /// Any attempt to set position public override long Position { - get - { - return inputStream.Position; - } - set - { - throw new NotSupportedException("TarInputStream Seek not supported"); - } + get { return inputStream.Position; } + set { throw new NotSupportedException("TarInputStream Seek not supported"); } } /// @@ -145,6 +132,15 @@ public override void Flush() inputStream.Flush(); } + /// + /// Flushes the baseInputStream + /// + /// + public override async Task FlushAsync(CancellationToken cancellationToken) + { + await inputStream.FlushAsync(cancellationToken); + } + /// /// Set the streams position. This operation is not supported and will throw a NotSupportedException /// @@ -198,16 +194,65 @@ public override void WriteByte(byte value) /// A byte cast to an int; -1 if the at the end of the stream. public override int ReadByte() { - byte[] oneByteBuffer = new byte[1]; - int num = Read(oneByteBuffer, 0, 1); + var oneByteBuffer = ArrayPool.Shared.Rent(1); + var num = Read(oneByteBuffer, 0, 1); if (num <= 0) { // return -1 to indicate that no byte was read. return -1; } - return oneByteBuffer[0]; + + var result = oneByteBuffer[0]; + ArrayPool.Shared.Return(oneByteBuffer); + return result; + } + + + /// + /// Reads bytes from the current tar archive entry. + /// + /// This method is aware of the boundaries of the current + /// entry in the archive and will deal with them appropriately + /// + /// + /// The buffer into which to place bytes read. + /// + /// + /// The offset at which to place bytes read. + /// + /// + /// The number of bytes to read. + /// + /// + /// + /// The number of bytes read, or 0 at end of stream/EOF. + /// + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return ReadAsync(buffer.AsMemory().Slice(offset, count), cancellationToken, true).AsTask(); } +#if NETSTANDARD2_1_OR_GREATER + /// + /// Reads bytes from the current tar archive entry. + /// + /// This method is aware of the boundaries of the current + /// entry in the archive and will deal with them appropriately + /// + /// + /// The buffer into which to place bytes read. + /// + /// + /// + /// The number of bytes read, or 0 at end of stream/EOF. + /// + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = + new CancellationToken()) + { + return ReadAsync(buffer, cancellationToken, true); + } +#endif + /// /// Reads bytes from the current tar archive entry. /// @@ -233,6 +278,13 @@ public override int Read(byte[] buffer, int offset, int count) throw new ArgumentNullException(nameof(buffer)); } + return ReadAsync(buffer.AsMemory().Slice(offset, count), CancellationToken.None, false).GetAwaiter() + .GetResult(); + } + + private async ValueTask ReadAsync(Memory buffer, CancellationToken ct, bool isAsync) + { + int offset = 0; int totalRead = 0; if (entryOffset >= entrySize) @@ -240,7 +292,7 @@ public override int Read(byte[] buffer, int offset, int count) return 0; } - long numToRead = count; + long numToRead = buffer.Length; if ((numToRead + entryOffset) > entrySize) { @@ -249,19 +301,22 @@ public override int Read(byte[] buffer, int offset, int count) if (readBuffer != null) { - int sz = (numToRead > readBuffer.Length) ? readBuffer.Length : (int)numToRead; + int sz = (numToRead > readBuffer.Memory.Length) ? readBuffer.Memory.Length : (int)numToRead; - Array.Copy(readBuffer, 0, buffer, offset, sz); + readBuffer.Memory.Slice(0, sz).CopyTo(buffer.Slice(offset, sz)); - if (sz >= readBuffer.Length) + if (sz >= readBuffer.Memory.Length) { + readBuffer.Dispose(); readBuffer = null; } else { - int newLen = readBuffer.Length - sz; - byte[] newBuf = new byte[newLen]; - Array.Copy(readBuffer, sz, newBuf, 0, newLen); + int newLen = readBuffer.Memory.Length - sz; + var newBuf = ExactMemoryPool.Shared.Rent(newLen); + readBuffer.Memory.Slice(sz, newLen).CopyTo(newBuf.Memory); + readBuffer.Dispose(); + readBuffer = newBuf; } @@ -270,28 +325,27 @@ public override int Read(byte[] buffer, int offset, int count) offset += sz; } + var recLen = TarBuffer.BlockSize; + var recBuf = ArrayPool.Shared.Rent(recLen); + while (numToRead > 0) { - byte[] rec = tarBuffer.ReadBlock(); - if (rec == null) - { - // Unexpected EOF! - throw new TarException("unexpected EOF with " + numToRead + " bytes unread"); - } + await tarBuffer.ReadBlockIntAsync(recBuf, ct, isAsync); var sz = (int)numToRead; - int recLen = rec.Length; if (recLen > sz) { - Array.Copy(rec, 0, buffer, offset, sz); - readBuffer = new byte[recLen - sz]; - Array.Copy(rec, sz, readBuffer, 0, recLen - sz); + recBuf.AsSpan().Slice(0, sz).CopyTo(buffer.Slice(offset, sz).Span); + readBuffer?.Dispose(); + + readBuffer = ExactMemoryPool.Shared.Rent(recLen - sz); + recBuf.AsSpan().Slice(sz, recLen - sz).CopyTo(readBuffer.Memory.Span); } else { sz = recLen; - Array.Copy(rec, 0, buffer, offset, recLen); + recBuf.AsSpan().CopyTo(buffer.Slice(offset, recLen).Span); } totalRead += sz; @@ -299,6 +353,8 @@ public override int Read(byte[] buffer, int offset, int count) offset += sz; } + ArrayPool.Shared.Return(recBuf); + entryOffset += totalRead; return totalRead; @@ -316,6 +372,17 @@ protected override void Dispose(bool disposing) } } +#if NETSTANDARD2_1_OR_GREATER + /// + /// Closes this stream. Calls the TarBuffer's close() method. + /// The underlying stream is closed by the TarBuffer. + /// + public override async ValueTask DisposeAsync() + { + await tarBuffer.CloseAsync(CancellationToken.None); + } +#endif + #endregion Stream Overrides /// @@ -359,10 +426,7 @@ public int GetRecordSize() /// public long Available { - get - { - return entrySize - entryOffset; - } + get { return entrySize - entryOffset; } } /// @@ -374,25 +438,42 @@ public long Available /// /// The number of bytes to skip. /// - public void Skip(long skipCount) + /// + private Task SkipAsync(long skipCount, CancellationToken ct) => SkipAsync(skipCount, ct, true).AsTask(); + + /// + /// Skip bytes in the input buffer. This skips bytes in the + /// current entry's data, not the entire archive, and will + /// stop at the end of the current entry's data if the number + /// to skip extends beyond that point. + /// + /// + /// The number of bytes to skip. + /// + private void Skip(long skipCount) => + SkipAsync(skipCount, CancellationToken.None, false).GetAwaiter().GetResult(); + + private async ValueTask SkipAsync(long skipCount, CancellationToken ct, bool isAsync) { // TODO: REVIEW efficiency of TarInputStream.Skip // This is horribly inefficient, but it ensures that we // properly skip over bytes via the TarBuffer... // - byte[] skipBuf = new byte[8 * 1024]; - - for (long num = skipCount; num > 0;) + var length = 8 * 1024; + using (var skipBuf = ExactMemoryPool.Shared.Rent(length)) { - int toRead = num > skipBuf.Length ? skipBuf.Length : (int)num; - int numRead = Read(skipBuf, 0, toRead); - - if (numRead == -1) + for (long num = skipCount; num > 0;) { - break; - } + int toRead = num > length ? length : (int)num; + int numRead = await ReadAsync(skipBuf.Memory.Slice(0, toRead), ct, isAsync); - num -= numRead; + if (numRead == -1) + { + break; + } + + num -= numRead; + } } } @@ -402,10 +483,7 @@ public void Skip(long skipCount) /// Currently marking is not supported, the return value is always false. public bool IsMarkSupported { - get - { - return false; - } + get { return false; } } /// @@ -438,7 +516,24 @@ public void Reset() /// /// The next TarEntry in the archive, or null. /// - public TarEntry GetNextEntry() + public Task GetNextEntryAsync(CancellationToken ct) => GetNextEntryAsync(ct, true).AsTask(); + + /// + /// Get the next entry in this tar archive. This will skip + /// over any remaining data in the current entry, if there + /// is one, and place the input stream at the header of the + /// next entry, and read the header and instantiate a new + /// TarEntry from the header bytes and return that entry. + /// If there are no more entries in the archive, null will + /// be returned to indicate that the end of the archive has + /// been reached. + /// + /// + /// The next TarEntry in the archive, or null. + /// + public TarEntry GetNextEntry() => GetNextEntryAsync(CancellationToken.None, true).GetAwaiter().GetResult(); + + private async ValueTask GetNextEntryAsync(CancellationToken ct, bool isAsync) { if (hasHitEOF) { @@ -447,21 +542,18 @@ public TarEntry GetNextEntry() if (currentEntry != null) { - SkipToNextEntry(); + await SkipToNextEntryAsync(ct, isAsync); } - byte[] headerBuf = tarBuffer.ReadBlock(); + byte[] headerBuf = ArrayPool.Shared.Rent(TarBuffer.BlockSize); + await tarBuffer.ReadBlockIntAsync(headerBuf, ct, isAsync); - if (headerBuf == null) - { - hasHitEOF = true; - } - else if (TarBuffer.IsEndOfArchiveBlock(headerBuf)) + if (TarBuffer.IsEndOfArchiveBlock(headerBuf)) { hasHitEOF = true; // Read the second zero-filled block - tarBuffer.ReadBlock(); + await tarBuffer.ReadBlockIntAsync(headerBuf, ct, isAsync); } else { @@ -471,6 +563,7 @@ public TarEntry GetNextEntry() if (hasHitEOF) { currentEntry = null; + readBuffer?.Dispose(); } else { @@ -482,50 +575,61 @@ public TarEntry GetNextEntry() { throw new TarException("Header checksum is invalid"); } + this.entryOffset = 0; this.entrySize = header.Size; - StringBuilder longName = null; + string longName = null; if (header.TypeFlag == TarHeader.LF_GNU_LONGNAME) { - byte[] nameBuffer = new byte[TarBuffer.BlockSize]; - long numToRead = this.entrySize; - - longName = new StringBuilder(); - - while (numToRead > 0) + using (var nameBuffer = ExactMemoryPool.Shared.Rent(TarBuffer.BlockSize)) { - int numRead = this.Read(nameBuffer, 0, (numToRead > nameBuffer.Length ? nameBuffer.Length : (int)numToRead)); + long numToRead = this.entrySize; - if (numRead == -1) + var longNameBuilder = StringBuilderPool.Instance.Rent(); + + while (numToRead > 0) { - throw new InvalidHeaderException("Failed to read long name entry"); + var length = (numToRead > TarBuffer.BlockSize ? TarBuffer.BlockSize : (int)numToRead); + int numRead = await ReadAsync(nameBuffer.Memory.Slice(0, length), ct, isAsync); + + if (numRead == -1) + { + throw new InvalidHeaderException("Failed to read long name entry"); + } + + longNameBuilder.Append(TarHeader.ParseName(nameBuffer.Memory.Slice(0, numRead).Span, + encoding)); + numToRead -= numRead; } - longName.Append(TarHeader.ParseName(nameBuffer, 0, numRead, encoding).ToString()); - numToRead -= numRead; - } + longName = longNameBuilder.ToString(); + StringBuilderPool.Instance.Return(longNameBuilder); - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); + await SkipToNextEntryAsync(ct, isAsync); + await this.tarBuffer.ReadBlockIntAsync(headerBuf, ct, isAsync); + } } else if (header.TypeFlag == TarHeader.LF_GHDR) - { // POSIX global extended header - // Ignore things we dont understand completely for now - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); + { + // POSIX global extended header + // Ignore things we dont understand completely for now + await SkipToNextEntryAsync(ct, isAsync); + await this.tarBuffer.ReadBlockIntAsync(headerBuf, ct, isAsync); } else if (header.TypeFlag == TarHeader.LF_XHDR) - { // POSIX extended header - byte[] nameBuffer = new byte[TarBuffer.BlockSize]; + { + // POSIX extended header + byte[] nameBuffer = ArrayPool.Shared.Rent(TarBuffer.BlockSize); long numToRead = this.entrySize; var xhr = new TarExtendedHeaderReader(); while (numToRead > 0) { - int numRead = this.Read(nameBuffer, 0, (numToRead > nameBuffer.Length ? nameBuffer.Length : (int)numToRead)); + var length = (numToRead > nameBuffer.Length ? nameBuffer.Length : (int)numToRead); + int numRead = await ReadAsync(nameBuffer.AsMemory().Slice(0, length), ct, isAsync); if (numRead == -1) { @@ -536,42 +640,47 @@ public TarEntry GetNextEntry() numToRead -= numRead; } + ArrayPool.Shared.Return(nameBuffer); + if (xhr.Headers.TryGetValue("path", out string name)) { - longName = new StringBuilder(name); + longName = name; } - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); + await SkipToNextEntryAsync(ct, isAsync); + await this.tarBuffer.ReadBlockIntAsync(headerBuf, ct, isAsync); } else if (header.TypeFlag == TarHeader.LF_GNU_VOLHDR) { // TODO: could show volume name when verbose - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); + await SkipToNextEntryAsync(ct, isAsync); + await this.tarBuffer.ReadBlockIntAsync(headerBuf, ct, isAsync); } else if (header.TypeFlag != TarHeader.LF_NORMAL && - header.TypeFlag != TarHeader.LF_OLDNORM && - header.TypeFlag != TarHeader.LF_LINK && - header.TypeFlag != TarHeader.LF_SYMLINK && - header.TypeFlag != TarHeader.LF_DIR) + header.TypeFlag != TarHeader.LF_OLDNORM && + header.TypeFlag != TarHeader.LF_LINK && + header.TypeFlag != TarHeader.LF_SYMLINK && + header.TypeFlag != TarHeader.LF_DIR) { // Ignore things we dont understand completely for now - SkipToNextEntry(); - headerBuf = tarBuffer.ReadBlock(); + await SkipToNextEntryAsync(ct, isAsync); + await tarBuffer.ReadBlockIntAsync(headerBuf, ct, isAsync); } if (entryFactory == null) { currentEntry = new TarEntry(headerBuf, encoding); + readBuffer?.Dispose(); + if (longName != null) { - currentEntry.Name = longName.ToString(); + currentEntry.Name = longName; } } else { currentEntry = entryFactory.CreateEntry(headerBuf); + readBuffer?.Dispose(); } // Magic was checked here for 'ustar' but there are multiple valid possibilities @@ -587,11 +696,16 @@ public TarEntry GetNextEntry() entrySize = 0; entryOffset = 0; currentEntry = null; + readBuffer?.Dispose(); + string errorText = string.Format("Bad header in record {0} block {1} {2}", tarBuffer.CurrentRecord, tarBuffer.CurrentBlock, ex.Message); throw new InvalidHeaderException(errorText); } } + + ArrayPool.Shared.Return(headerBuf); + return currentEntry; } @@ -602,30 +716,55 @@ public TarEntry GetNextEntry() /// /// The OutputStream into which to write the entry's data. /// - public void CopyEntryContents(Stream outputStream) + /// + public Task CopyEntryContentsAsync(Stream outputStream, CancellationToken ct) => + CopyEntryContentsAsync(outputStream, ct, true).AsTask(); + + /// + /// Copies the contents of the current tar archive entry directly into + /// an output stream. + /// + /// + /// The OutputStream into which to write the entry's data. + /// + public void CopyEntryContents(Stream outputStream) => + CopyEntryContentsAsync(outputStream, CancellationToken.None, false).GetAwaiter().GetResult(); + + private async ValueTask CopyEntryContentsAsync(Stream outputStream, CancellationToken ct, bool isAsync) { - byte[] tempBuffer = new byte[32 * 1024]; + byte[] tempBuffer = ArrayPool.Shared.Rent(32 * 1024); while (true) { - int numRead = Read(tempBuffer, 0, tempBuffer.Length); + int numRead = await ReadAsync(tempBuffer, ct, isAsync); if (numRead <= 0) { break; } - outputStream.Write(tempBuffer, 0, numRead); + + if (isAsync) + { + await outputStream.WriteAsync(tempBuffer, 0, numRead, ct); + } + else + { + outputStream.Write(tempBuffer, 0, numRead); + } } + + ArrayPool.Shared.Return(tempBuffer); } - private void SkipToNextEntry() + private async ValueTask SkipToNextEntryAsync(CancellationToken ct, bool isAsync) { long numToSkip = entrySize - entryOffset; if (numToSkip > 0) { - Skip(numToSkip); + await SkipAsync(numToSkip, ct, isAsync); } + readBuffer?.Dispose(); readBuffer = null; } @@ -676,6 +815,7 @@ public interface IEntryFactory public class EntryFactoryAdapter : IEntryFactory { Encoding nameEncoding; + /// /// Construct standard entry factory class with ASCII name encoding /// @@ -683,6 +823,7 @@ public class EntryFactoryAdapter : IEntryFactory public EntryFactoryAdapter() { } + /// /// Construct standard entry factory with name encoding /// @@ -691,6 +832,7 @@ public EntryFactoryAdapter(Encoding nameEncoding) { this.nameEncoding = nameEncoding; } + /// /// Create a based on named /// @@ -742,7 +884,7 @@ public TarEntry CreateEntry(byte[] headerBuffer) /// /// Buffer used with calls to Read() /// - protected byte[] readBuffer; + protected IMemoryOwner readBuffer; /// /// Working buffer diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs b/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs index 7c52e6c7c..9ce13f15d 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarOutputStream.cs @@ -1,6 +1,9 @@ using System; +using System.Buffers; using System.IO; using System.Text; +using System.Threading; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tar { @@ -50,8 +53,8 @@ public TarOutputStream(Stream outputStream, int blockFactor) this.outputStream = outputStream; buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); - assemblyBuffer = new byte[TarBuffer.BlockSize]; - blockBuffer = new byte[TarBuffer.BlockSize]; + assemblyBuffer = ArrayPool.Shared.Rent(TarBuffer.BlockSize); + blockBuffer = ArrayPool.Shared.Rent(TarBuffer.BlockSize); } /// @@ -70,8 +73,8 @@ public TarOutputStream(Stream outputStream, int blockFactor, Encoding nameEncodi this.outputStream = outputStream; buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); - assemblyBuffer = new byte[TarBuffer.BlockSize]; - blockBuffer = new byte[TarBuffer.BlockSize]; + assemblyBuffer = ArrayPool.Shared.Rent(TarBuffer.BlockSize); + blockBuffer = ArrayPool.Shared.Rent(TarBuffer.BlockSize); this.nameEncoding = nameEncoding; } @@ -94,10 +97,7 @@ public bool IsStreamOwner /// public override bool CanRead { - get - { - return outputStream.CanRead; - } + get { return outputStream.CanRead; } } /// @@ -105,10 +105,7 @@ public override bool CanRead /// public override bool CanSeek { - get - { - return outputStream.CanSeek; - } + get { return outputStream.CanSeek; } } /// @@ -116,10 +113,7 @@ public override bool CanSeek /// public override bool CanWrite { - get - { - return outputStream.CanWrite; - } + get { return outputStream.CanWrite; } } /// @@ -127,10 +121,7 @@ public override bool CanWrite /// public override long Length { - get - { - return outputStream.Length; - } + get { return outputStream.Length; } } /// @@ -138,14 +129,8 @@ public override long Length /// public override long Position { - get - { - return outputStream.Position; - } - set - { - outputStream.Position = value; - } + get { return outputStream.Position; } + set { outputStream.Position = value; } } /// @@ -193,6 +178,23 @@ public override int Read(byte[] buffer, int offset, int count) return outputStream.Read(buffer, offset, count); } + /// + /// read bytes from the current stream and advance the position within the + /// stream by the number of bytes read. + /// + /// The buffer to store read bytes in. + /// The index into the buffer to being storing bytes at. + /// The desired number of bytes to read. + /// + /// The total number of bytes read, or zero if at the end of the stream. + /// The number of bytes may be less than the count + /// requested if data is not available. + public override async Task ReadAsync(byte[] buffer, int offset, int count, + CancellationToken cancellationToken) + { + return await outputStream.ReadAsync(buffer, offset, count, cancellationToken); + } + /// /// All buffered data is written to destination /// @@ -201,17 +203,34 @@ public override void Flush() outputStream.Flush(); } + /// + /// All buffered data is written to destination + /// + public override async Task FlushAsync(CancellationToken cancellationToken) + { + await outputStream.FlushAsync(cancellationToken); + } + /// /// Ends the TAR archive without closing the underlying OutputStream. /// The result is that the EOF block of nulls is written. /// - public void Finish() + public void Finish() => FinishAsync(CancellationToken.None, false).GetAwaiter().GetResult(); + + /// + /// Ends the TAR archive without closing the underlying OutputStream. + /// The result is that the EOF block of nulls is written. + /// + public Task FinishAsync(CancellationToken cancellationToken) => FinishAsync(cancellationToken, true); + + private async Task FinishAsync(CancellationToken cancellationToken, bool isAsync) { if (IsEntryOpen) { - CloseEntry(); + await CloseEntryAsync(cancellationToken, isAsync); } - WriteEofBlock(); + + await WriteEofBlockAsync(cancellationToken, isAsync); } /// @@ -226,6 +245,9 @@ protected override void Dispose(bool disposing) isClosed = true; Finish(); buffer.Close(); + + ArrayPool.Shared.Return(assemblyBuffer); + ArrayPool.Shared.Return(blockBuffer); } } @@ -269,44 +291,70 @@ private bool IsEntryOpen /// /// The TarEntry to be written to the archive. /// - public void PutNextEntry(TarEntry entry) + /// + public Task PutNextEntryAsync(TarEntry entry, CancellationToken cancellationToken) => + PutNextEntryAsync(entry, cancellationToken, true); + + /// + /// Put an entry on the output stream. This writes the entry's + /// header and positions the output stream for writing + /// the contents of the entry. Once this method is called, the + /// stream is ready for calls to write() to write the entry's + /// contents. Once the contents are written, closeEntry() + /// MUST be called to ensure that all buffered data + /// is completely written to the output stream. + /// + /// + /// The TarEntry to be written to the archive. + /// + public void PutNextEntry(TarEntry entry) => + PutNextEntryAsync(entry, CancellationToken.None, false).GetAwaiter().GetResult(); + + private async Task PutNextEntryAsync(TarEntry entry, CancellationToken cancellationToken, bool isAsync) { if (entry == null) { throw new ArgumentNullException(nameof(entry)); } - var namelen = nameEncoding != null ? nameEncoding.GetByteCount(entry.TarHeader.Name) : entry.TarHeader.Name.Length; + var namelen = nameEncoding != null + ? nameEncoding.GetByteCount(entry.TarHeader.Name) + : entry.TarHeader.Name.Length; if (namelen > TarHeader.NAMELEN) { var longHeader = new TarHeader(); longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME; longHeader.Name = longHeader.Name + "././@LongLink"; - longHeader.Mode = 420;//644 by default + longHeader.Mode = 420; //644 by default longHeader.UserId = entry.UserId; longHeader.GroupId = entry.GroupId; longHeader.GroupName = entry.GroupName; longHeader.UserName = entry.UserName; longHeader.LinkName = ""; - longHeader.Size = namelen + 1; // Plus one to avoid dropping last char + longHeader.Size = namelen + 1; // Plus one to avoid dropping last char longHeader.WriteHeader(blockBuffer, nameEncoding); - buffer.WriteBlock(blockBuffer); // Add special long filename header block + // Add special long filename header block + await buffer.WriteBlockAsync(blockBuffer, 0, cancellationToken, isAsync); int nameCharIndex = 0; - while (nameCharIndex < namelen + 1 /* we've allocated one for the null char, now we must make sure it gets written out */) + while + (nameCharIndex < + namelen + 1 /* we've allocated one for the null char, now we must make sure it gets written out */) { Array.Clear(blockBuffer, 0, blockBuffer.Length); - TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize, nameEncoding); // This func handles OK the extra char out of string length + TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, + TarBuffer.BlockSize, nameEncoding); // This func handles OK the extra char out of string length nameCharIndex += TarBuffer.BlockSize; - buffer.WriteBlock(blockBuffer); + + await buffer.WriteBlockAsync(blockBuffer, 0, cancellationToken, isAsync); } } entry.WriteEntryHeader(blockBuffer, nameEncoding); - buffer.WriteBlock(blockBuffer); + await buffer.WriteBlockAsync(blockBuffer, 0, cancellationToken, isAsync); currBytes = 0; @@ -322,13 +370,26 @@ public void PutNextEntry(TarEntry entry) /// to the output stream before this entry is closed and the /// next entry written. /// - public void CloseEntry() + public Task CloseEntryAsync(CancellationToken cancellationToken) => CloseEntryAsync(cancellationToken, true); + + /// + /// Close an entry. This method MUST be called for all file + /// entries that contain data. The reason is that we must + /// buffer data written to the stream in order to satisfy + /// the buffer's block based writes. Thus, there may be + /// data fragments still being assembled that must be written + /// to the output stream before this entry is closed and the + /// next entry written. + /// + public void CloseEntry() => CloseEntryAsync(CancellationToken.None, true).GetAwaiter().GetResult(); + + private async Task CloseEntryAsync(CancellationToken cancellationToken, bool isAsync) { if (assemblyBufferLength > 0) { Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength); - buffer.WriteBlock(assemblyBuffer); + await buffer.WriteBlockAsync(assemblyBuffer, 0, cancellationToken, isAsync); currBytes += assemblyBufferLength; assemblyBufferLength = 0; @@ -352,7 +413,10 @@ public void CloseEntry() /// public override void WriteByte(byte value) { - Write(new byte[] { value }, 0, 1); + var oneByteArray = ArrayPool.Shared.Rent(1); + oneByteArray[0] = value; + Write(oneByteArray, 0, 1); + ArrayPool.Shared.Return(oneByteArray); } /// @@ -373,7 +437,32 @@ public override void WriteByte(byte value) /// /// The number of bytes to write. /// - public override void Write(byte[] buffer, int offset, int count) + public override void Write(byte[] buffer, int offset, int count) => + WriteAsync(buffer, offset, count, CancellationToken.None, false).GetAwaiter().GetResult(); + + /// + /// Writes bytes to the current tar archive entry. This method + /// is aware of the current entry and will throw an exception if + /// you attempt to write bytes past the length specified for the + /// current entry. The method is also (painfully) aware of the + /// record buffering required by TarBuffer, and manages buffers + /// that are not a multiple of recordsize in length, including + /// assembling records from small buffers. + /// + /// + /// The buffer to write to the archive. + /// + /// + /// The offset in the buffer from which to get bytes. + /// + /// + /// The number of bytes to write. + /// + /// + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(buffer, offset, count, cancellationToken, true); + + private async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool isAsync) { if (buffer == null) { @@ -418,7 +507,7 @@ public override void Write(byte[] buffer, int offset, int count) Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength); Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen); - this.buffer.WriteBlock(blockBuffer); + await this.buffer.WriteBlockAsync(blockBuffer, 0, cancellationToken, isAsync); currBytes += blockBuffer.Length; @@ -450,7 +539,7 @@ public override void Write(byte[] buffer, int offset, int count) break; } - this.buffer.WriteBlock(buffer, offset); + await this.buffer.WriteBlockAsync(buffer, offset, cancellationToken, isAsync); int bufferLength = blockBuffer.Length; currBytes += bufferLength; @@ -463,11 +552,11 @@ public override void Write(byte[] buffer, int offset, int count) /// Write an EOF (end of archive) block to the tar archive. /// The end of the archive is indicated by two blocks consisting entirely of zero bytes. /// - private void WriteEofBlock() + private async Task WriteEofBlockAsync(CancellationToken cancellationToken, bool isAsync) { Array.Clear(blockBuffer, 0, blockBuffer.Length); - buffer.WriteBlock(blockBuffer); - buffer.WriteBlock(blockBuffer); + await buffer.WriteBlockAsync(blockBuffer, 0, cancellationToken, isAsync); + await buffer.WriteBlockAsync(blockBuffer, 0, cancellationToken, isAsync); } #region Instance Fields diff --git a/test/ICSharpCode.SharpZipLib.Tests/Core/StringBuilderPoolTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Core/StringBuilderPoolTests.cs new file mode 100644 index 000000000..85d8c65a9 --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/Core/StringBuilderPoolTests.cs @@ -0,0 +1,77 @@ +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Core; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.Core +{ + [TestFixture] + public class StringBuilderPoolTests + { + [Test] + [Category("Core")] + public void RoundTrip() + { + var pool = new StringBuilderPool(); + var builder1 = pool.Rent(); + pool.Return(builder1); + var builder2 = pool.Rent(); + Assert.AreEqual(builder1, builder2); + } + + [Test] + [Category("Core")] + public void ReturnsClears() + { + var pool = new StringBuilderPool(); + var builder1 = pool.Rent(); + builder1.Append("Hello"); + pool.Return(builder1); + Assert.AreEqual(0, builder1.Length); + } + + [Test] + [Category("Core")] + public async Task ThreadSafeAsync() + { + // use a lot of threads to increase the likelihood of errors + var concurrency = 100; + + var pool = new StringBuilderPool(); + var gate = new TaskCompletionSource(); + var startedTasks = new Task[concurrency]; + var completedTasks = new Task[concurrency]; + for (int i = 0; i < concurrency; i++) + { + var started = new TaskCompletionSource(); + startedTasks[i] = started.Task; + var captured = i; + completedTasks[i] = Task.Run(async () => + { + started.SetResult(true); + await gate.Task; + var builder = pool.Rent(); + builder.Append("Hello "); + builder.Append(captured); + var str = builder.ToString(); + pool.Return(builder); + return str; + }); + } + + // make sure all the threads have started + await Task.WhenAll(startedTasks); + + // let them all loose at the same time + gate.SetResult(true); + + // make sure every thread produces the expected string and hence had its own StringBuilder + var results = await Task.WhenAll(completedTasks); + for (int i = 0; i < concurrency; i++) + { + var result = results[i]; + Assert.AreEqual($"Hello {i}", result); + } + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarBufferTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarBufferTests.cs new file mode 100644 index 000000000..3974ffb5b --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarBufferTests.cs @@ -0,0 +1,125 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Tar; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.Tar +{ + [TestFixture] + public class TarBufferTests + { + [Test] + public void TestSimpleReadWrite() + { + var ms = new MemoryStream(); + var reader = TarBuffer.CreateInputTarBuffer(ms, 1); + var writer = TarBuffer.CreateOutputTarBuffer(ms, 1); + writer.IsStreamOwner = false; + + var block = new byte[TarBuffer.BlockSize]; + var r = new Random(); + r.NextBytes(block); + + writer.WriteBlock(block); + writer.WriteBlock(block); + writer.WriteBlock(block); + writer.Close(); + + ms.Seek(0, SeekOrigin.Begin); + + var block0 = reader.ReadBlock(); + var block1 = reader.ReadBlock(); + var block2 = reader.ReadBlock(); + Assert.AreEqual(block, block0); + Assert.AreEqual(block, block1); + Assert.AreEqual(block, block2); + writer.Close(); + } + + [Test] + public void TestSkipBlock() + { + var ms = new MemoryStream(); + var reader = TarBuffer.CreateInputTarBuffer(ms, 1); + var writer = TarBuffer.CreateOutputTarBuffer(ms, 1); + writer.IsStreamOwner = false; + + var block0 = new byte[TarBuffer.BlockSize]; + var block1 = new byte[TarBuffer.BlockSize]; + var r = new Random(); + r.NextBytes(block0); + r.NextBytes(block1); + + writer.WriteBlock(block0); + writer.WriteBlock(block1); + writer.Close(); + + ms.Seek(0, SeekOrigin.Begin); + + reader.SkipBlock(); + var block = reader.ReadBlock(); + Assert.AreEqual(block, block1); + writer.Close(); + } + + [Test] + public async Task TestSimpleReadWriteAsync() + { + var ms = new MemoryStream(); + var reader = TarBuffer.CreateInputTarBuffer(ms, 1); + var writer = TarBuffer.CreateOutputTarBuffer(ms, 1); + writer.IsStreamOwner = false; + + var block = new byte[TarBuffer.BlockSize]; + var r = new Random(); + r.NextBytes(block); + + await writer.WriteBlockAsync(block, CancellationToken.None); + await writer.WriteBlockAsync(block, CancellationToken.None); + await writer.WriteBlockAsync(block, CancellationToken.None); + await writer.CloseAsync(CancellationToken.None); + + ms.Seek(0, SeekOrigin.Begin); + + var block0 = new byte[TarBuffer.BlockSize]; + await reader.ReadBlockIntAsync(block0, CancellationToken.None, true); + var block1 = new byte[TarBuffer.BlockSize]; + await reader.ReadBlockIntAsync(block1, CancellationToken.None, true); + var block2 = new byte[TarBuffer.BlockSize]; + await reader.ReadBlockIntAsync(block2, CancellationToken.None, true); + Assert.AreEqual(block, block0); + Assert.AreEqual(block, block1); + Assert.AreEqual(block, block2); + await writer.CloseAsync(CancellationToken.None); + } + + [Test] + public async Task TestSkipBlockAsync() + { + var ms = new MemoryStream(); + var reader = TarBuffer.CreateInputTarBuffer(ms, 1); + var writer = TarBuffer.CreateOutputTarBuffer(ms, 1); + writer.IsStreamOwner = false; + + var block0 = new byte[TarBuffer.BlockSize]; + var block1 = new byte[TarBuffer.BlockSize]; + var r = new Random(); + r.NextBytes(block0); + r.NextBytes(block1); + + await writer.WriteBlockAsync(block0, CancellationToken.None); + await writer.WriteBlockAsync(block1, CancellationToken.None); + await writer.CloseAsync(CancellationToken.None); + + ms.Seek(0, SeekOrigin.Begin); + + await reader.SkipBlockAsync(CancellationToken.None); + var block = new byte[TarBuffer.BlockSize]; + await reader.ReadBlockIntAsync(block, CancellationToken.None, true); + Assert.AreEqual(block, block1); + await writer.CloseAsync(CancellationToken.None); + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarInputStreamTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarInputStreamTests.cs new file mode 100644 index 000000000..83457834f --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarInputStreamTests.cs @@ -0,0 +1,91 @@ +using System; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Tar; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.Tar +{ + public class TarInputStreamTests + { + [Test] + public void TestRead() + { + var entryBytes = new byte[2000]; + var r = new Random(); + r.NextBytes(entryBytes); + using var ms = new MemoryStream(); + using (var tos = new TarOutputStream(ms, Encoding.UTF8) { IsStreamOwner = false }) + { + var e = TarEntry.CreateTarEntry("some entry"); + e.Size = entryBytes.Length; + tos.PutNextEntry(e); + tos.Write(entryBytes, 0, entryBytes.Length); + tos.CloseEntry(); + } + + ms.Seek(0, SeekOrigin.Begin); + + using var tis = new TarInputStream(ms, Encoding.UTF8); + var entry = tis.GetNextEntry(); + Assert.AreEqual("some entry", entry.Name); + var buffer = new byte[1000]; // smaller than 2 blocks + var read0 = tis.Read(buffer, 0, buffer.Length); + Assert.AreEqual(1000, read0); + Assert.AreEqual(entryBytes.AsSpan(0, 1000).ToArray(), buffer); + + var read1 = tis.Read(buffer, 0, 5); + Assert.AreEqual(5, read1); + Assert.AreEqual(entryBytes.AsSpan(1000, 5).ToArray(), buffer.AsSpan().Slice(0, 5).ToArray()); + + var read2 = tis.Read(buffer, 0, 20); + Assert.AreEqual(20, read2); + Assert.AreEqual(entryBytes.AsSpan(1005, 20).ToArray(), buffer.AsSpan().Slice(0, 20).ToArray()); + + var read3 = tis.Read(buffer, 0, 975); + Assert.AreEqual(975, read3); + Assert.AreEqual(entryBytes.AsSpan(1025, 975).ToArray(), buffer.AsSpan().Slice(0, 975).ToArray()); + } + + [Test] + public async Task TestReadAsync() + { + var entryBytes = new byte[2000]; + var r = new Random(); + r.NextBytes(entryBytes); + using var ms = new MemoryStream(); + using (var tos = new TarOutputStream(ms, Encoding.UTF8) { IsStreamOwner = false }) + { + var e = TarEntry.CreateTarEntry("some entry"); + e.Size = entryBytes.Length; + await tos.PutNextEntryAsync(e, CancellationToken.None); + await tos.WriteAsync(entryBytes, 0, entryBytes.Length); + await tos.CloseEntryAsync(CancellationToken.None); + } + + ms.Seek(0, SeekOrigin.Begin); + + using var tis = new TarInputStream(ms, Encoding.UTF8); + var entry = await tis.GetNextEntryAsync(CancellationToken.None); + Assert.AreEqual("some entry", entry.Name); + var buffer = new byte[1000]; // smaller than 2 blocks + var read0 = await tis.ReadAsync(buffer, 0, buffer.Length); + Assert.AreEqual(1000, read0); + Assert.AreEqual(entryBytes.AsSpan(0, 1000).ToArray(), buffer); + + var read1 = await tis.ReadAsync(buffer, 0, 5); + Assert.AreEqual(5, read1); + Assert.AreEqual(entryBytes.AsSpan(1000, 5).ToArray(), buffer.AsSpan().Slice(0, 5).ToArray()); + + var read2 = await tis.ReadAsync(buffer, 0, 20); + Assert.AreEqual(20, read2); + Assert.AreEqual(entryBytes.AsSpan(1005, 20).ToArray(), buffer.AsSpan().Slice(0, 20).ToArray()); + + var read3 = await tis.ReadAsync(buffer, 0, 975); + Assert.AreEqual(975, read3); + Assert.AreEqual(entryBytes.AsSpan(1025, 975).ToArray(), buffer.AsSpan().Slice(0, 975).ToArray()); + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs index fae87a736..d1f1f89bc 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs @@ -5,6 +5,8 @@ using System; using System.IO; using System.Text; +using System.Threading; +using System.Threading.Tasks; using NUnit.Framework.Internal; namespace ICSharpCode.SharpZipLib.Tests.Tar @@ -110,12 +112,12 @@ public void BlockFactorHandling() var offset = blockNumber % TarBuffer.BlockSize; Assert.AreEqual(0, tarData[byteIndex], "Trailing block data should be null iteration {0} block {1} offset {2} index {3}", - factor, blockNumber, offset, byteIndex); + factor, blockNumber, offset, byteIndex); byteIndex += 1; } } } - + /// /// Check that the tar trailer only contains nulls. /// @@ -843,7 +845,7 @@ public void ParseHeaderWithEncoding(int length, string encodingName) [TestCase(100, "shift-jis")] [TestCase(128, "shift-jis")] [Category("Tar")] - public void StreamWithJapaneseName(int length, string encodingName) + public async Task StreamWithJapaneseNameAsync(int length, string encodingName) { // U+3042 is Japanese Hiragana // https://unicode.org/charts/PDF/U3040.pdf @@ -859,13 +861,14 @@ public void StreamWithJapaneseName(int length, string encodingName) tarOutput.PutNextEntry(entry); tarOutput.Write(data, 0, data.Length); } + using(var memInput = new MemoryStream(memoryStream.ToArray())) using(var inputStream = new TarInputStream(memInput, encoding)) { var buf = new byte[64]; - var entry = inputStream.GetNextEntry(); + var entry = await inputStream.GetNextEntryAsync(CancellationToken.None); Assert.AreEqual(entryName, entry.Name); - var bytesread = inputStream.Read(buf, 0, buf.Length); + var bytesread = await inputStream.ReadAsync(buf, 0, buf.Length, CancellationToken.None); Assert.AreEqual(data.Length, bytesread); } File.WriteAllBytes(Path.Combine(Path.GetTempPath(), $"jpnametest_{length}_{encodingName}.tar"), memoryStream.ToArray()); From b5b1b07ddcf3de350d62924a76f7c65d143f6362 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 24 May 2022 16:51:11 +0200 Subject: [PATCH 145/162] fix(zip): skip reading position for non-seekable async streams (#754) --- .../Zip/ZipOutputStream.cs | 3 ++- .../TestSupport/Streams.cs | 12 ++++++----- .../Zip/StreamHandling.cs | 7 +++---- .../Zip/ZipStreamAsyncTests.cs | 21 +++++++++++++++++++ 4 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 36349c886..3f77fbe80 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -521,9 +521,10 @@ internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0, public async Task PutNextEntryAsync(ZipEntry entry, CancellationToken ct = default) { if (curEntry != null) await CloseEntryAsync(ct); + var position = CanPatchEntries ? baseOutputStream_.Position : -1; await baseOutputStream_.WriteProcToStreamAsync(s => { - PutNextEntry(s, entry, baseOutputStream_.Position); + PutNextEntry(s, entry, position); }, ct); if (!entry.IsCrypted) return; diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Streams.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Streams.cs index 3f5ae552a..f6b0fff3e 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Streams.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Streams.cs @@ -177,13 +177,15 @@ public class MemoryStreamWithoutSeek : TrackedMemoryStream /// /// /// true if the stream is open. - public override bool CanSeek + public override bool CanSeek => false; + + /// + public override long Position { - get - { - return false; - } + get => throw new NotSupportedException("Getting position is not supported"); + set => throw new NotSupportedException("Setting position is not supported"); } + } /// diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index 2f1e866fd..d96d32713 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -111,11 +111,10 @@ public void ReadAndWriteZip64NonSeekable() outStream.Close(); } - Assert.That(msw.ToArray(), Does.PassTestArchive()); - - msw.Position = 0; + var msBytes = msw.ToArray(); + Assert.That(msBytes, Does.PassTestArchive()); - using (var zis = new ZipInputStream(msw)) + using (var zis = new ZipInputStream(new MemoryStream(msBytes))) { while (zis.GetNextEntry() != null) { diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs index 5eb33c063..9a8aeac14 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs @@ -97,5 +97,26 @@ public async Task WriteZipStreamWithZipCryptoAsync() ZipTesting.AssertValidZip(ms, password, false); } + [Test] + [Category("Zip")] + [Category("Async")] + public async Task WriteReadOnlyZipStreamAsync () + { + using var ms = new MemoryStreamWithoutSeek(); + + using(var outStream = new ZipOutputStream(ms) { IsStreamOwner = false }) + { + await outStream.PutNextEntryAsync(new ZipEntry("FirstFile")); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.PutNextEntryAsync(new ZipEntry("SecondFile")); + await Utils.WriteDummyDataAsync(outStream, 12); + + await outStream.FinishAsync(CancellationToken.None); + } + + ZipTesting.AssertValidZip(new MemoryStream(ms.ToArray())); + } + } } From a41e066e42161d556caad4824f18bb75ddfb3f2e Mon Sep 17 00:00:00 2001 From: Yihezkel Schoenbrun Date: Thu, 11 Aug 2022 15:14:27 +0300 Subject: [PATCH 146/162] fix(zip): explicitly specify hash method for Rfc2898DeriveBytes (#765) --- src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs index 5aced2d71..6c84be691 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs @@ -76,7 +76,11 @@ public ZipAESTransform(string key, byte[] saltBytes, int blockSize, bool writeMo _encrPos = ENCRYPT_BLOCK; // Performs the equivalent of derive_key in Dr Brian Gladman's pwd2key.c +#if NET472_OR_GREATER || NETSTANDARD2_1_OR_GREATER || NETCOREAPP2_0_OR_GREATER + var pdb = new Rfc2898DeriveBytes(key, saltBytes, KEY_ROUNDS, HashAlgorithmName.SHA1); +#else var pdb = new Rfc2898DeriveBytes(key, saltBytes, KEY_ROUNDS); +#endif var rm = Aes.Create(); rm.Mode = CipherMode.ECB; // No feedback from cipher for CTR mode _counterNonce = new byte[_blockSize]; @@ -160,7 +164,7 @@ public byte[] GetAuthCode() /// public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { - if(inputCount > 0) + if (inputCount > 0) { throw new NotImplementedException("TransformFinalBlock is not implemented and inputCount is greater than 0"); } From 7411f3a515a06e4840ef8650f2c9d8fe3e313fa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 14 Aug 2022 10:39:42 +0200 Subject: [PATCH 147/162] fix(tar): read full extended headers (#675) * fix(tar): read full extended headers * Update src/ICSharpCode.SharpZipLib/Tar/TarExtendedHeaderReader.cs --- .../Tar/TarExtendedHeaderReader.cs | 37 ++++++++++++++++--- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarExtendedHeaderReader.cs b/src/ICSharpCode.SharpZipLib/Tar/TarExtendedHeaderReader.cs index d1d438ad0..b711e6d54 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarExtendedHeaderReader.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarExtendedHeaderReader.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Text; namespace ICSharpCode.SharpZipLib.Tar @@ -26,7 +27,10 @@ public class TarExtendedHeaderReader private int state = LENGTH; - private static readonly byte[] StateNext = new[] { (byte)' ', (byte)'=', (byte)'\n' }; + private int currHeaderLength; + private int currHeaderRead; + + private static readonly byte[] StateNext = { (byte)' ', (byte)'=', (byte)'\n' }; /// /// Creates a new . @@ -46,23 +50,46 @@ public void Read(byte[] buffer, int length) for (int i = 0; i < length; i++) { byte next = buffer[i]; + + var foundStateEnd = state == VALUE + ? currHeaderRead == currHeaderLength -1 + : next == StateNext[state]; - if (next == StateNext[state]) + if (foundStateEnd) { Flush(); headerParts[state] = sb.ToString(); sb.Clear(); - + if (++state == END) { - headers.Add(headerParts[KEY], headerParts[VALUE]); + if (!headers.ContainsKey(headerParts[KEY])) + { + headers.Add(headerParts[KEY], headerParts[VALUE]); + } + headerParts = new string[3]; + currHeaderLength = 0; + currHeaderRead = 0; state = LENGTH; } + else + { + currHeaderRead++; + } + + + if (state != VALUE) continue; + + if (int.TryParse(headerParts[LENGTH], out var vl)) + { + currHeaderLength = vl; + } } else { byteBuffer[bbIndex++] = next; + currHeaderRead++; if (bbIndex == 4) Flush(); } From 79614c5fd8c49d639e7fb367a861d548e646e85d Mon Sep 17 00:00:00 2001 From: Yihezkel Schoenbrun Date: Tue, 16 Aug 2022 09:09:02 +0300 Subject: [PATCH 148/162] fix: replace uses of obsolete method `RNGCryptoServiceProvider` (#766) Replace insecure obsolete method (new RNGCryptoServiceProvider()) with RandomNumberGenerator.Create() in PkzipClassic, ZipFile and ZipOutputStream. See docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rngcryptoserviceprovider?view=net-6.0 and dotnet/runtime#40169 --- src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs | 4 ++-- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs b/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs index 6730c9dee..1c7bd1f28 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs @@ -6,7 +6,7 @@ namespace ICSharpCode.SharpZipLib.Encryption { /// /// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives. - /// While it has been superceded by more recent and more powerful algorithms, its still in use and + /// While it has been superseded by more recent and more powerful algorithms, its still in use and /// is viable for preventing casual snooping /// public abstract class PkzipClassic : SymmetricAlgorithm @@ -444,7 +444,7 @@ public override byte[] Key public override void GenerateKey() { key_ = new byte[12]; - using (var rng = new RNGCryptoServiceProvider()) + using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(key_); } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index ce216dacc..eae3e2960 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -3781,7 +3781,7 @@ private static void CheckClassicPassword(CryptoStream classicCryptoStream, ZipEn private static void WriteEncryptionHeader(Stream stream, long crcValue) { byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; - using (var rng = new RNGCryptoServiceProvider()) + using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(cryptBuffer); } diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 3f77fbe80..21042f75a 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -723,7 +723,7 @@ private byte[] CreateZipCryptoHeader(long crcValue) InitializeZipCryptoPassword(Password); byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; - using (var rng = new RNGCryptoServiceProvider()) + using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(cryptBuffer); } @@ -808,11 +808,11 @@ public override void Write(byte[] buffer, int offset, int count) private void CopyAndEncrypt(byte[] buffer, int offset, int count) { - const int CopyBufferSize = 4096; - byte[] localBuffer = new byte[CopyBufferSize]; + const int copyBufferSize = 4096; + byte[] localBuffer = new byte[copyBufferSize]; while (count > 0) { - int bufferCount = (count < CopyBufferSize) ? count : CopyBufferSize; + int bufferCount = (count < copyBufferSize) ? count : copyBufferSize; Array.Copy(buffer, offset, localBuffer, 0, bufferCount); EncryptBlock(localBuffer, 0, bufferCount); From bdec7778f1b27b25dcae43a68b4d5c1e41491768 Mon Sep 17 00:00:00 2001 From: sensslen Date: Tue, 16 Aug 2022 11:19:22 +0200 Subject: [PATCH 149/162] fix(tar): enable unix paths in tar RootPath (#582) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: nils måsén Co-authored-by: Simon Ensslen --- src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs | 7 +-- src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs | 7 +-- .../Tar/TarStringExtension.cs | 13 +++++ .../Tar/TarTests.cs | 48 +++++++++++++++++-- 4 files changed, 63 insertions(+), 12 deletions(-) create mode 100644 src/ICSharpCode.SharpZipLib/Tar/TarStringExtension.cs diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs index 6db6b23b9..878649017 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarArchive.cs @@ -356,8 +356,7 @@ public string RootPath { throw new ObjectDisposedException("TarArchive"); } - // Convert to forward slashes for matching. Trim trailing / for correct final path - rootPath = value.Replace('\\', '/').TrimEnd('/'); + rootPath = value.ToTarArchivePath().TrimEnd('/'); } } @@ -660,7 +659,9 @@ private void ExtractEntry(string destDir, TarEntry entry, bool allowParentTraver string destFile = Path.Combine(destDir, name); var destFileDir = Path.GetDirectoryName(Path.GetFullPath(destFile)) ?? ""; - if (!allowParentTraversal && !destFileDir.StartsWith(destDir, StringComparison.InvariantCultureIgnoreCase)) + var isRootDir = entry.IsDirectory && entry.Name == ""; + + if (!allowParentTraversal && !isRootDir && !destFileDir.StartsWith(destDir, StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidNameException("Parent traversal in paths is not allowed"); } diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs index 2f3cf7862..82c813367 100644 --- a/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Tar/TarEntry.cs @@ -372,15 +372,10 @@ public void GetFileTarHeader(TarHeader header, string file) } */ - name = name.Replace(Path.DirectorySeparatorChar, '/'); - // No absolute pathnames // Windows (and Posix?) paths can start with UNC style "\\NetworkDrive\", // so we loop on starting /'s. - while (name.StartsWith("/", StringComparison.Ordinal)) - { - name = name.Substring(1); - } + name = name.ToTarArchivePath(); header.LinkName = String.Empty; header.Name = name; diff --git a/src/ICSharpCode.SharpZipLib/Tar/TarStringExtension.cs b/src/ICSharpCode.SharpZipLib/Tar/TarStringExtension.cs new file mode 100644 index 000000000..433c6a424 --- /dev/null +++ b/src/ICSharpCode.SharpZipLib/Tar/TarStringExtension.cs @@ -0,0 +1,13 @@ +using System.IO; +using ICSharpCode.SharpZipLib.Core; + +namespace ICSharpCode.SharpZipLib.Tar +{ + internal static class TarStringExtension + { + public static string ToTarArchivePath(this string s) + { + return PathUtils.DropPathRoot(s).Replace(Path.DirectorySeparatorChar, '/'); + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs index d1f1f89bc..c6a35ff08 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Tar/TarTests.cs @@ -833,7 +833,7 @@ public void ParseHeaderWithEncoding(int length, string encodingName) reparseHeader.ParseBuffer(headerbytes, enc); Assert.AreEqual(name, reparseHeader.Name); // top 100 bytes are name field in tar header - for (int i = 0;i < encodedName.Length;i++) + for (int i = 0; i < encodedName.Length; i++) { Assert.AreEqual(encodedName[i], headerbytes[i]); } @@ -852,9 +852,9 @@ public async Task StreamWithJapaneseNameAsync(int length, string encodingName) var entryName = new string((char)0x3042, length); var data = new byte[32]; var encoding = Encoding.GetEncoding(encodingName); - using(var memoryStream = new MemoryStream()) + using (var memoryStream = new MemoryStream()) { - using(var tarOutput = new TarOutputStream(memoryStream, encoding)) + using (var tarOutput = new TarOutputStream(memoryStream, encoding)) { var entry = TarEntry.CreateTarEntry(entryName); entry.Size = 32; @@ -874,5 +874,47 @@ public async Task StreamWithJapaneseNameAsync(int length, string encodingName) File.WriteAllBytes(Path.Combine(Path.GetTempPath(), $"jpnametest_{length}_{encodingName}.tar"), memoryStream.ToArray()); } } + /// + /// This test could be considered integration test. it creates a tar archive with the root directory specified + /// Then extracts it and compares the two folders. This used to fail on unix due to issues with root folder handling + /// in the tar archive. + /// + [Test] + [Category("Tar")] + public void RootPathIsRespected() + { + using (var extractDirectory = new TempDir()) + using (var tarFileName = new TempFile()) + using (var tempDirectory = new TempDir()) + { + tempDirectory.CreateDummyFile(); + + using (var tarFile = File.Open(tarFileName.FullName, FileMode.Create)) + { + using (var tarOutputStream = TarArchive.CreateOutputTarArchive(tarFile)) + { + tarOutputStream.RootPath = tempDirectory.FullName; + var entry = TarEntry.CreateEntryFromFile(tempDirectory.FullName); + tarOutputStream.WriteEntry(entry, true); + } + } + + using (var file = File.OpenRead(tarFileName.FullName)) + { + using (var archive = TarArchive.CreateInputTarArchive(file, Encoding.UTF8)) + { + archive.ExtractContents(extractDirectory.FullName); + } + } + + var expectationDirectory = new DirectoryInfo(tempDirectory.FullName); + foreach (var checkFile in expectationDirectory.GetFiles("", SearchOption.AllDirectories)) + { + var relativePath = checkFile.FullName.Substring(expectationDirectory.FullName.Length + 1); + FileAssert.Exists(Path.Combine(extractDirectory.FullName, relativePath)); + FileAssert.AreEqual(checkFile.FullName, Path.Combine(extractDirectory.FullName, relativePath)); + } + } + } } } From 519ed7367daf0a5ad7f2d36bee6e994ffcd7e9e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Tue, 16 Aug 2022 12:01:04 +0200 Subject: [PATCH 150/162] fix(zip): handle iterating updated entries in ZipInputStream (#642) --- .../Zip/ZipInputStream.cs | 71 +++++++++++++------ .../TestSupport/Utils.cs | 37 +++++++++- .../Zip/StreamHandling.cs | 46 ++++++++++++ 3 files changed, 132 insertions(+), 22 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs index 1b5b0ad53..e49ebddfb 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs @@ -3,6 +3,7 @@ using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using System; +using System.Diagnostics; using System.IO; namespace ICSharpCode.SharpZipLib.Zip @@ -181,31 +182,12 @@ public ZipEntry GetNextEntry() CloseEntry(); } - int header = inputBuffer.ReadLeInt(); - - if (header == ZipConstants.CentralHeaderSignature || - header == ZipConstants.EndOfCentralDirectorySignature || - header == ZipConstants.CentralHeaderDigitalSignature || - header == ZipConstants.ArchiveExtraDataSignature || - header == ZipConstants.Zip64CentralFileHeaderSignature) + if (!SkipUntilNextEntry()) { - // No more individual entries exist Dispose(); return null; } - // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found - // Spanning signature is same as descriptor signature and is untested as yet. - if ((header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature)) - { - header = inputBuffer.ReadLeInt(); - } - - if (header != ZipConstants.LocalHeaderSignature) - { - throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header)); - } - var versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); flags = inputBuffer.ReadLeShort(); @@ -303,6 +285,54 @@ public ZipEntry GetNextEntry() return entry; } + /// + /// Reads bytes from the input stream until either a local file header signature, or another signature + /// indicating that no more entries should be present, is found. + /// + /// Thrown if the end of the input stream is reached without any signatures found + /// Returns whether the found signature is for a local entry header + private bool SkipUntilNextEntry() + { + // First let's skip all null bytes since it's the sane padding to add when updating an entry with smaller size + var paddingSkipped = 0; + while(inputBuffer.ReadLeByte() == 0) { + paddingSkipped++; + } + + // Last byte read was not actually consumed, restore the offset + inputBuffer.Available += 1; + if(paddingSkipped > 0) { + Debug.WriteLine("Skipped {0} null byte(s) before reading signature", paddingSkipped); + } + + var offset = 0; + // Read initial header quad directly after the last entry + var header = (uint)inputBuffer.ReadLeInt(); + do + { + switch (header) + { + case ZipConstants.CentralHeaderSignature: + case ZipConstants.EndOfCentralDirectorySignature: + case ZipConstants.CentralHeaderDigitalSignature: + case ZipConstants.ArchiveExtraDataSignature: + case ZipConstants.Zip64CentralFileHeaderSignature: + Debug.WriteLine("Non-entry signature found at offset {0,2}: 0x{1:x8}", offset, header); + // No more individual entries exist + return false; + + case ZipConstants.LocalHeaderSignature: + Debug.WriteLine("Entry local header signature found at offset {0,2}: 0x{1:x8}", offset, header); + return true; + default: + // Current header quad did not match any signature, shift in another byte + header = (uint) (inputBuffer.ReadLeByte() << 24) | (header >> 8); + offset++; + break; + } + } while (true); // Loop until we either get an EOF exception or we find the next signature + } + /// /// Read data descriptor at the end of compressed data. /// @@ -400,6 +430,7 @@ public void CloseEntry() if ((inputBuffer.Available > csize) && (csize >= 0)) { + // Buffer can contain entire entry data. Internally offsetting position inside buffer inputBuffer.Available = (int)((long)inputBuffer.Available - csize); } else diff --git a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs index 3c5788b8a..f610660ee 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/TestSupport/Utils.cs @@ -1,6 +1,9 @@ using NUnit.Framework; using System; +using System.Diagnostics; using System.IO; +using System.Text; +using ICSharpCode.SharpZipLib.Tests.Zip; using System.Linq; using System.Threading.Tasks; @@ -11,7 +14,10 @@ namespace ICSharpCode.SharpZipLib.Tests.TestSupport /// public static class Utils { + public static int DummyContentLength = 16; + internal const int DefaultSeed = 5; + private static Random random = new Random(DefaultSeed); /// /// Returns the system root for the current platform (usually c:\ for windows and / for others) @@ -115,6 +121,30 @@ public static string GetDummyFileName() /// /// public static TempFile GetTempFile() => new TempFile(); + + public static void PatchFirstEntrySize(Stream stream, int newSize) + { + using(stream) + { + var sizeBytes = BitConverter.GetBytes(newSize); + + stream.Seek(18, SeekOrigin.Begin); + stream.Write(sizeBytes, 0, 4); + stream.Write(sizeBytes, 0, 4); + } + } + } + + public class TestTraceListener : TraceListener + { + private readonly TextWriter _writer; + public TestTraceListener(TextWriter writer) + { + _writer = writer; + } + + public override void WriteLine(string message) => _writer.WriteLine(message); + public override void Write(string message) => _writer.Write(message); } public class TempFile : FileSystemInfo, IDisposable @@ -137,6 +167,8 @@ public override void Delete() _fileInfo.Delete(); } + public FileStream Open(FileMode mode, FileAccess access) => _fileInfo.Open(mode, access); + public FileStream Open(FileMode mode) => _fileInfo.Open(mode); public FileStream Create() => _fileInfo.Create(); public static TempFile WithDummyData(int size, string dirPath = null, string filename = null, int seed = Utils.DefaultSeed) @@ -182,9 +214,10 @@ public void Dispose() } #endregion IDisposable Support - - } + + + public class TempDir : FileSystemInfo, IDisposable { public override string Name => Path.GetFileName(FullName); diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs index d96d32713..3e8ab732c 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/StreamHandling.cs @@ -3,7 +3,10 @@ using ICSharpCode.SharpZipLib.Zip; using NUnit.Framework; using System; +using System.Diagnostics; using System.IO; +using System.Linq; +using System.Text; using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; namespace ICSharpCode.SharpZipLib.Tests.Zip @@ -14,6 +17,12 @@ namespace ICSharpCode.SharpZipLib.Tests.Zip [TestFixture] public class StreamHandling : ZipBase { + private TestTraceListener Listener; + [SetUp] + public void Init() => Trace.Listeners.Add(Listener = new TestTraceListener(TestContext.Out)); + [TearDown] + public void Deinit() => Trace.Listeners.Remove(Listener); + private void MustFailRead(Stream s, byte[] buffer, int offset, int count) { bool exception = false; @@ -540,5 +549,42 @@ public void ShouldThrowDescriptiveExceptionOnUncompressedDescriptorEntry() }); } } + + [Test] + [Category("Zip")] + public void IteratingOverEntriesInDirectUpdatedArchive([Values(0x0, 0x80)] byte padding) + { + using (var tempFile = new TempFile()) + { + using (var zf = ZipFile.Create(tempFile)) + { + zf.BeginUpdate(); + // Add a "large" file, where the bottom 1023 bytes will become padding + var contentsAndPadding = Enumerable.Repeat(padding, count: 1024).ToArray(); + zf.Add(new MemoryDataSource(contentsAndPadding), "FirstFile", CompressionMethod.Stored); + // Add a second file after the first one + zf.Add(new StringMemoryDataSource("fileContents"), "SecondFile", CompressionMethod.Stored); + zf.CommitUpdate(); + } + + // Since ZipFile doesn't support UpdateCommand.Modify yet we'll have to simulate it by patching the header + Utils.PatchFirstEntrySize(tempFile.Open(FileMode.Open), 1); + + // Iterate updated entries + using (var fs = File.OpenRead(tempFile)) + using (var zis = new ZipInputStream(fs)) + { + var firstEntry = zis.GetNextEntry(); + Assert.NotNull(firstEntry); + Assert.AreEqual(1, firstEntry.CompressedSize); + Assert.AreEqual(1, firstEntry.Size); + + var secondEntry = zis.GetNextEntry(); + Assert.NotNull(secondEntry, "Zip entry following padding not found"); + var contents = new StreamReader(zis, Encoding.UTF8, false, 128, true).ReadToEnd(); + Assert.AreEqual("fileContents", contents); + } + } + } } } From b314d3d5cdb2abae949a78d17c2de28bd28dc216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Thu, 15 Sep 2022 12:18:55 +0200 Subject: [PATCH 151/162] feat(gzip): add GzipOutputStream async support (#672) --- .../GZip/GzipOutputStream.cs | 171 +++++++++++++----- .../Streams/DeflaterOutputStream.cs | 2 +- .../GZip/GZipAsyncTests.cs | 144 +++++++++++++++ .../GZip/GZipTests.cs | 22 +-- .../Zip/ZipStreamAsyncTests.cs | 11 +- 5 files changed, 279 insertions(+), 71 deletions(-) create mode 100644 test/ICSharpCode.SharpZipLib.Tests/GZip/GZipAsyncTests.cs diff --git a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs index 0b1a647fe..456ec928e 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs @@ -3,7 +3,9 @@ using ICSharpCode.SharpZipLib.Zip.Compression.Streams; using System; using System.IO; -using System.Text; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.GZip { @@ -184,6 +186,30 @@ protected override void Dispose(bool disposing) } } } + +#if NETSTANDARD2_1_OR_GREATER + /// + public override async ValueTask DisposeAsync() + { + try + { + await FinishAsync(CancellationToken.None); + } + finally + { + if (state_ != OutputState.Closed) + { + state_ = OutputState.Closed; + if (IsStreamOwner) + { + await baseOutputStream_.DisposeAsync(); + } + } + + await base.DisposeAsync(); + } + } +#endif /// /// Flushes the stream by ensuring the header is written, and then calling Flush @@ -218,74 +244,119 @@ public override void Finish() { state_ = OutputState.Finished; base.Finish(); - - var totalin = (uint)(deflater_.TotalIn & 0xffffffff); - var crcval = (uint)(crc.Value & 0xffffffff); - - byte[] gzipFooter; - - unchecked - { - gzipFooter = new byte[] { - (byte) crcval, (byte) (crcval >> 8), - (byte) (crcval >> 16), (byte) (crcval >> 24), - - (byte) totalin, (byte) (totalin >> 8), - (byte) (totalin >> 16), (byte) (totalin >> 24) - }; - } - + var gzipFooter = GetFooter(); baseOutputStream_.Write(gzipFooter, 0, gzipFooter.Length); } } + + /// + public override async Task FlushAsync(CancellationToken ct) + { + await WriteHeaderAsync(); + await base.FlushAsync(ct); + } + + + /// + public override async Task FinishAsync(CancellationToken ct) + { + // If no data has been written a header should be added. + if (state_ == OutputState.Header) + { + await WriteHeaderAsync(); + } + + if (state_ == OutputState.Footer) + { + state_ = OutputState.Finished; + await base.FinishAsync(ct); + var gzipFooter = GetFooter(); + await baseOutputStream_.WriteAsync(gzipFooter, 0, gzipFooter.Length, ct); + } + } #endregion DeflaterOutputStream overrides #region Support Routines - private static string CleanFilename(string path) - => path.Substring(path.LastIndexOf('/') + 1); - - private void WriteHeader() + private byte[] GetFooter() { - if (state_ == OutputState.Header) - { - state_ = OutputState.Footer; + var totalin = (uint)(deflater_.TotalIn & 0xffffffff); + var crcval = (uint)(crc.Value & 0xffffffff); - var mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals - byte[] gzipHeader = { - // The two magic bytes - GZipConstants.ID1, - GZipConstants.ID2, + byte[] gzipFooter; - // The compression type - GZipConstants.CompressionMethodDeflate, + unchecked + { + gzipFooter = new [] { + (byte) crcval, + (byte) (crcval >> 8), + (byte) (crcval >> 16), + (byte) (crcval >> 24), + (byte) totalin, + (byte) (totalin >> 8), + (byte) (totalin >> 16), + (byte) (totalin >> 24), + }; + } - // The flags (not set) - (byte)flags, + return gzipFooter; + } - // The modification time - (byte) mod_time, (byte) (mod_time >> 8), - (byte) (mod_time >> 16), (byte) (mod_time >> 24), + private byte[] GetHeader() + { + var modTime = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals + byte[] gzipHeader = { + // The two magic bytes + GZipConstants.ID1, + GZipConstants.ID2, - // The extra flags - 0, + // The compression type + GZipConstants.CompressionMethodDeflate, - // The OS type (unknown) - 255 - }; + // The flags (not set) + (byte)flags, - baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length); + // The modification time + (byte) modTime, (byte) (modTime >> 8), + (byte) (modTime >> 16), (byte) (modTime >> 24), - if (flags.HasFlag(GZipFlags.FNAME)) - { - var fname = GZipConstants.Encoding.GetBytes(fileName); - baseOutputStream_.Write(fname, 0, fname.Length); + // The extra flags + 0, - // End filename string with a \0 - baseOutputStream_.Write(new byte[] { 0 }, 0, 1); - } + // The OS type (unknown) + 255 + }; + + if (!flags.HasFlag(GZipFlags.FNAME)) + { + return gzipHeader; } + + + return gzipHeader + .Concat(GZipConstants.Encoding.GetBytes(fileName)) + .Concat(new byte []{0}) // End filename string with a \0 + .ToArray(); + } + + private static string CleanFilename(string path) + => path.Substring(path.LastIndexOf('/') + 1); + + private void WriteHeader() + { + if (state_ != OutputState.Header) return; + state_ = OutputState.Footer; + var gzipHeader = GetHeader(); + baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length); + } + + private async Task WriteHeaderAsync() + { + if (state_ != OutputState.Header) return; + state_ = OutputState.Footer; + var gzipHeader = GetHeader(); + await baseOutputStream_.WriteAsync(gzipHeader, 0, gzipHeader.Length); } #endregion Support Routines diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs index 1c54b6848..a9b78dd75 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs @@ -412,7 +412,7 @@ protected override void Dispose(bool disposing) } } -#if NETSTANDARD2_1 +#if NETSTANDARD2_1_OR_GREATER /// /// Calls and closes the underlying /// stream when is true. diff --git a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipAsyncTests.cs b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipAsyncTests.cs new file mode 100644 index 000000000..209ae15d4 --- /dev/null +++ b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipAsyncTests.cs @@ -0,0 +1,144 @@ +using System.IO; +using System.Text; +using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.GZip; +using ICSharpCode.SharpZipLib.Tests.TestSupport; +using NUnit.Framework; + +namespace ICSharpCode.SharpZipLib.Tests.GZip +{ + + + [TestFixture] + public class GZipAsyncTests + { + [Test] + [Category("GZip")] + [Category("Async")] + public async Task SmallBufferDecompressionAsync([Values(0, 1, 3)] int seed) + { + var outputBufferSize = 100000; + var outputBuffer = new byte[outputBufferSize]; + var inputBuffer = Utils.GetDummyBytes(outputBufferSize * 4, seed); + +#if NETCOREAPP3_1_OR_GREATER + await using var msGzip = new MemoryStream(); + await using (var gzos = new GZipOutputStream(msGzip){IsStreamOwner = false}) + { + await gzos.WriteAsync(inputBuffer, 0, inputBuffer.Length); + } + + msGzip.Seek(0, SeekOrigin.Begin); + + using (var gzis = new GZipInputStream(msGzip)) + await using (var msRaw = new MemoryStream()) + { + int readOut; + while ((readOut = gzis.Read(outputBuffer, 0, outputBuffer.Length)) > 0) + { + await msRaw.WriteAsync(outputBuffer, 0, readOut); + } + + var resultBuffer = msRaw.ToArray(); + for (var i = 0; i < resultBuffer.Length; i++) + { + Assert.AreEqual(inputBuffer[i], resultBuffer[i]); + } + } +#else + using var msGzip = new MemoryStream(); + using (var gzos = new GZipOutputStream(msGzip){IsStreamOwner = false}) + { + await gzos.WriteAsync(inputBuffer, 0, inputBuffer.Length); + } + + msGzip.Seek(0, SeekOrigin.Begin); + + using (var gzis = new GZipInputStream(msGzip)) + using (var msRaw = new MemoryStream()) + { + int readOut; + while ((readOut = gzis.Read(outputBuffer, 0, outputBuffer.Length)) > 0) + { + await msRaw.WriteAsync(outputBuffer, 0, readOut); + } + + var resultBuffer = msRaw.ToArray(); + for (var i = 0; i < resultBuffer.Length; i++) + { + Assert.AreEqual(inputBuffer[i], resultBuffer[i]); + } + } +#endif + } + + /// + /// Basic compress/decompress test + /// + [Test] + [Category("GZip")] + [Category("Async")] + public async Task OriginalFilenameAsync() + { + var content = "FileContents"; + +#if NETCOREAPP3_1_OR_GREATER + await using var ms = new MemoryStream(); + await using (var outStream = new GZipOutputStream(ms) { IsStreamOwner = false }) + { + outStream.FileName = "/path/to/file.ext"; + outStream.Write(Encoding.ASCII.GetBytes(content)); + } +#else + var ms = new MemoryStream(); + var outStream = new GZipOutputStream(ms){ IsStreamOwner = false }; + outStream.FileName = "/path/to/file.ext"; + var bytes = Encoding.ASCII.GetBytes(content); + outStream.Write(bytes, 0, bytes.Length); + await outStream.FinishAsync(System.Threading.CancellationToken.None); + outStream.Dispose(); + +#endif + ms.Seek(0, SeekOrigin.Begin); + + using (var inStream = new GZipInputStream(ms)) + { + var readBuffer = new byte[content.Length]; + inStream.Read(readBuffer, 0, readBuffer.Length); + Assert.AreEqual(content, Encoding.ASCII.GetString(readBuffer)); + Assert.AreEqual("file.ext", inStream.GetFilename()); + } + } + + /// + /// Test creating an empty gzip stream using async + /// + [Test] + [Category("GZip")] + [Category("Async")] + public async Task EmptyGZipStreamAsync() + { +#if NETCOREAPP3_1_OR_GREATER + await using var ms = new MemoryStream(); + await using (var outStream = new GZipOutputStream(ms) { IsStreamOwner = false }) + { + // No content + } +#else + var ms = new MemoryStream(); + var outStream = new GZipOutputStream(ms){ IsStreamOwner = false }; + await outStream.FinishAsync(System.Threading.CancellationToken.None); + outStream.Dispose(); + +#endif + ms.Seek(0, SeekOrigin.Begin); + + using (var inStream = new GZipInputStream(ms)) + using (var reader = new StreamReader(inStream)) + { + var content = await reader.ReadToEndAsync(); + Assert.IsEmpty(content); + } + } + } +} diff --git a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs index 62be609fc..3241fd134 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/GZip/GZipTests.cs @@ -4,6 +4,8 @@ using System; using System.IO; using System.Text; +using System.Threading; +using System.Threading.Tasks; namespace ICSharpCode.SharpZipLib.Tests.GZip { @@ -386,32 +388,23 @@ public void FlushToUnderlyingStream() [Test] [Category("GZip")] - public void SmallBufferDecompression() + public void SmallBufferDecompression([Values(0, 1, 3)] int seed) { var outputBufferSize = 100000; - var inputBufferSize = outputBufferSize * 4; - var inputBuffer = Utils.GetDummyBytes(inputBufferSize, seed: 0); - var outputBuffer = new byte[outputBufferSize]; + var inputBuffer = Utils.GetDummyBytes(outputBufferSize * 4, seed); using var msGzip = new MemoryStream(); - using (var gzos = new GZipOutputStream(msGzip)) + using (var gzos = new GZipOutputStream(msGzip){IsStreamOwner = false}) { - gzos.IsStreamOwner = false; - gzos.Write(inputBuffer, 0, inputBuffer.Length); - - gzos.Flush(); - gzos.Finish(); } msGzip.Seek(0, SeekOrigin.Begin); - - + using (var gzis = new GZipInputStream(msGzip)) using (var msRaw = new MemoryStream()) { - int readOut; while ((readOut = gzis.Read(outputBuffer, 0, outputBuffer.Length)) > 0) { @@ -419,13 +412,10 @@ public void SmallBufferDecompression() } var resultBuffer = msRaw.ToArray(); - for (var i = 0; i < resultBuffer.Length; i++) { Assert.AreEqual(inputBuffer[i], resultBuffer[i]); } - - } } diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs index 9a8aeac14..aff027bf1 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipStreamAsyncTests.cs @@ -1,8 +1,8 @@ using System.IO; using System.Threading; using System.Threading.Tasks; -using ICSharpCode.SharpZipLib.Tests.TestSupport; using ICSharpCode.SharpZipLib.Zip; +using ICSharpCode.SharpZipLib.Tests.TestSupport; using NUnit.Framework; namespace ICSharpCode.SharpZipLib.Tests.Zip @@ -10,12 +10,12 @@ namespace ICSharpCode.SharpZipLib.Tests.Zip [TestFixture] public class ZipStreamAsyncTests { -#if NETCOREAPP3_1_OR_GREATER [Test] [Category("Zip")] [Category("Async")] public async Task WriteZipStreamUsingAsync() { +#if NETCOREAPP3_1_OR_GREATER await using var ms = new MemoryStream(); await using (var outStream = new ZipOutputStream(ms){IsStreamOwner = false}) @@ -28,8 +28,11 @@ public async Task WriteZipStreamUsingAsync() } ZipTesting.AssertValidZip(ms); - } +#else + await Task.CompletedTask; + Assert.Ignore("Async Using is not supported"); #endif + } [Test] [Category("Zip")] @@ -119,4 +122,4 @@ public async Task WriteReadOnlyZipStreamAsync () } } -} +} \ No newline at end of file From cea8b0dc154c71040ff74d731ff55c451e8dc59d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 11:19:17 +0200 Subject: [PATCH 152/162] prepare for v1.4.0 (#755) changes needed for the upcoming release, mainly related to .NET 6 compatibility --- .github/workflows/build-test.yml | 27 ++--- .../ICSharpCode.SharpZipLib.Benchmark.csproj | 2 +- .../Encryption/ZipAESStream.cs | 2 +- .../Encryption/ZipAESTransform.cs | 106 +++++------------- .../ICSharpCode.SharpZipLib.csproj | 19 ++-- .../ICSharpCode.SharpZipLib.Tests.csproj | 8 +- 6 files changed, 54 insertions(+), 110 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index d5630331f..463b5d6fb 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -18,11 +18,8 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, windows-2019, macos-latest] - target: [netstandard2.0, netstandard2.1] - include: - - os: windows-2019 - target: net45 + os: [ubuntu-latest, windows-latest, macos-latest] + target: [netstandard2.0, netstandard2.1, net6.0] env: LIB_PROJ: src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj steps: @@ -31,10 +28,10 @@ jobs: ref: ${{ github.events.inputs.tag }} fetch-depth: 0 - - name: Setup .NET Core + - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '3.1.x' + dotnet-version: '6.0.x' - name: Show .NET info run: dotnet --info @@ -52,17 +49,17 @@ jobs: matrix: # Windows testing is combined with code coverage os: [ubuntu, macos] - target: [netcoreapp3.1] + target: [net6.0] steps: - uses: actions/checkout@v2 with: fetch-depth: 0 - name: Setup .NET Core - if: matrix.target == 'netcoreapp3.1' + if: matrix.target == 'net6.0' uses: actions/setup-dotnet@v1 with: - dotnet-version: '3.1.x' + dotnet-version: '6.0.x' - name: Restore test dependencies run: dotnet restore @@ -89,7 +86,7 @@ jobs: - name: Setup .NET uses: actions/setup-dotnet@v1 with: - dotnet-version: '3.1.x' + dotnet-version: '6.0.x' # NOTE: This is the temporary fix for https://github.com/actions/virtual-environments/issues/1090 - name: Cleanup before restore @@ -120,7 +117,7 @@ jobs: Pack: needs: [Build, Test, CodeCov] - runs-on: windows-2019 + runs-on: windows-latest env: PKG_SUFFIX: '' PKG_PROJ: src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -135,14 +132,14 @@ jobs: - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: - dotnet-version: '5.0.x' + dotnet-version: '6.0.x' - name: Build library for .NET Standard 2.0 run: dotnet build -c Release -f netstandard2.0 ${{ env.PKG_PROPS }} ${{ env.PKG_PROJ }} - name: Build library for .NET Standard 2.1 run: dotnet build -c Release -f netstandard2.1 ${{ env.PKG_PROPS }} ${{ env.PKG_PROJ }} - - name: Build library for .NET Framework 4.5 - run: dotnet build -c Release -f net45 ${{ env.PKG_PROPS }} ${{ env.PKG_PROJ }} + - name: Build library for .NET 6.0 + run: dotnet build -c Release -f net6.0 ${{ env.PKG_PROPS }} ${{ env.PKG_PROJ }} - name: Add PR suffix to package if: ${{ github.event_name == 'pull_request' }} diff --git a/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj b/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj index 81a8ad598..7688d0ff2 100644 --- a/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj +++ b/benchmark/ICSharpCode.SharpZipLib.Benchmark/ICSharpCode.SharpZipLib.Benchmark.csproj @@ -2,7 +2,7 @@ Exe - netcoreapp2.1;netcoreapp3.1;net461 + net6.0;netcoreapp3.1;net462 diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs index 80ce0b4ab..346b5484b 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs @@ -40,7 +40,7 @@ public ZipAESStream(Stream stream, ZipAESTransform transform, CryptoStreamMode m } // The final n bytes of the AES stream contain the Auth Code. - private const int AUTH_CODE_LENGTH = 10; + public const int AUTH_CODE_LENGTH = 10; // Blocksize is always 16 here, even for AES-256 which has transform.InputBlockSize of 32. private const int CRYPTO_BLOCK_SIZE = 16; diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs index 6c84be691..32c7b8156 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs @@ -1,6 +1,5 @@ using System; using System.Security.Cryptography; -using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Encryption { @@ -9,31 +8,6 @@ namespace ICSharpCode.SharpZipLib.Encryption /// internal class ZipAESTransform : ICryptoTransform { -#if NET45 - class IncrementalHash : HMACSHA1 - { - bool _finalised; - public IncrementalHash(byte[] key) : base(key) { } - public static IncrementalHash CreateHMAC(string n, byte[] key) => new IncrementalHash(key); - public void AppendData(byte[] buffer, int offset, int count) => TransformBlock(buffer, offset, count, buffer, offset); - public byte[] GetHashAndReset() - { - if (!_finalised) - { - byte[] dummy = new byte[0]; - TransformFinalBlock(dummy, 0, 0); - _finalised = true; - } - return Hash; - } - } - - static class HashAlgorithmName - { - public static string SHA1 = null; - } -#endif - private const int PWD_VER_LENGTH = 2; // WinZip use iteration count of 1000 for PBKDF2 key generation @@ -137,91 +111,67 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b /// /// Returns the 2 byte password verifier /// - public byte[] PwdVerifier - { - get - { - return _pwdVerifier; - } - } + public byte[] PwdVerifier => _pwdVerifier; /// /// Returns the 10 byte AUTH CODE to be checked or appended immediately following the AES data stream. /// - public byte[] GetAuthCode() - { - if (_authCode == null) - { - _authCode = _hmacsha1.GetHashAndReset(); - } - return _authCode; - } + public byte[] GetAuthCode() => _authCode ?? (_authCode = _hmacsha1.GetHashAndReset()); #region ICryptoTransform Members /// - /// Not implemented. + /// Transform final block and read auth code /// public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { - if (inputCount > 0) - { - throw new NotImplementedException("TransformFinalBlock is not implemented and inputCount is greater than 0"); + var buffer = Array.Empty(); + + // FIXME: When used together with `ZipAESStream`, the final block handling is done inside of it instead + // This should not be necessary anymore, and the entire `ZipAESStream` class should be replaced with a plain `CryptoStream` + if (inputCount != 0) { + if (inputCount > ZipAESStream.AUTH_CODE_LENGTH) + { + // At least one byte of data is preceeding the auth code + int finalBlock = inputCount - ZipAESStream.AUTH_CODE_LENGTH; + buffer = new byte[finalBlock]; + TransformBlock(inputBuffer, inputOffset, finalBlock, buffer, 0); + } + else if (inputCount < ZipAESStream.AUTH_CODE_LENGTH) + throw new Zip.ZipException("Auth code missing from input stream"); + + // Read the authcode from the last 10 bytes + _authCode = _hmacsha1.GetHashAndReset(); } - return Empty.Array(); + + + return buffer; } /// /// Gets the size of the input data blocks in bytes. /// - public int InputBlockSize - { - get - { - return _blockSize; - } - } + public int InputBlockSize => _blockSize; /// /// Gets the size of the output data blocks in bytes. /// - public int OutputBlockSize - { - get - { - return _blockSize; - } - } + public int OutputBlockSize => _blockSize; /// /// Gets a value indicating whether multiple blocks can be transformed. /// - public bool CanTransformMultipleBlocks - { - get - { - return true; - } - } + public bool CanTransformMultipleBlocks => true; /// /// Gets a value indicating whether the current transform can be reused. /// - public bool CanReuseTransform - { - get - { - return true; - } - } + public bool CanReuseTransform => true; /// /// Cleanup internal state. /// - public void Dispose() - { - _encryptor.Dispose(); - } + public void Dispose() => _encryptor.Dispose(); #endregion ICryptoTransform Members } diff --git a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj index e736ad1cc..0dfc04003 100644 --- a/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj +++ b/src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj @@ -1,8 +1,10 @@  - netstandard2.0;netstandard2.1;net45 - True + netstandard2.0;netstandard2.1;net6.0 + true + true + true ../../assets/ICSharpCode.SharpZipLib.snk true true @@ -11,8 +13,8 @@ - 1.3.3 - $(Version).11 + 1.4.0 + $(Version).12 $(FileVersion) SharpZipLib ICSharpCode @@ -22,11 +24,11 @@ http://icsharpcode.github.io/SharpZipLib/ images/sharpziplib-nuget-256x256.png https://github.com/icsharpcode/SharpZipLib - Copyright © 2000-2021 SharpZipLib Contributors + Copyright © 2000-2022 SharpZipLib Contributors Compression Library Zip GZip BZip2 LZW Tar en-US -Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.3 for more information. +Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.4.0 for more information. https://github.com/icsharpcode/SharpZipLib @@ -34,11 +36,6 @@ Please see https://github.com/icsharpcode/SharpZipLib/wiki/Release-1.3.3 for mor - - - - - diff --git a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj index 4a46e84f2..73ef2eb0d 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj +++ b/test/ICSharpCode.SharpZipLib.Tests/ICSharpCode.SharpZipLib.Tests.csproj @@ -2,7 +2,7 @@ Library - netcoreapp3.1;net46 + net6.0;net462 true @@ -13,9 +13,9 @@ - - - + + + From 3c1b3ba0cf719d87b6c72d99be6fa9c6e0a3a355 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 13:16:26 +0200 Subject: [PATCH 153/162] docs: fix circular refs and target fw (#775) --- docs/help/docfx.json | 4 ++-- src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/FastZip.cs | 2 +- src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/help/docfx.json b/docs/help/docfx.json index b2123cfa2..1da3079e4 100644 --- a/docs/help/docfx.json +++ b/docs/help/docfx.json @@ -16,7 +16,7 @@ ], "dest": "api", "properties": { - "TargetFramework": "NETSTANDARD2" + "TargetFramework": "netstandard2.0" } } ], @@ -65,7 +65,7 @@ ], "globalMetadata": { "_appTitle": "SharpZipLib Help", - "_appFooter": "Copyright © 2000-2019 SharpZipLib Contributors", + "_appFooter": "Copyright © 2000-2022 SharpZipLib Contributors", "_gitContribute": { "repo": "https://github.com/icsharpcode/SharpZipLib", "branch": "master" diff --git a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs index 456ec928e..ade624818 100644 --- a/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs @@ -188,7 +188,7 @@ protected override void Dispose(bool disposing) } #if NETSTANDARD2_1_OR_GREATER - /// + /// public override async ValueTask DisposeAsync() { try diff --git a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs index 13aedb021..29185cbec 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/FastZip.cs @@ -361,7 +361,7 @@ public int LegacyCodePage set => _stringCodec.CodePage = value; } - /// + /// public StringCodec StringCodec { get => _stringCodec; diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs index eae3e2960..3abe9516b 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipFile.cs @@ -739,7 +739,7 @@ public Encoding ZipCryptoEncoding set => _stringCodec.ZipCryptoEncoding = value; } - /// + /// public StringCodec StringCodec { get => _stringCodec; From 338d57ac3f7ca65ecfce8576e1f4d1cc7b6258a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 13:22:42 +0200 Subject: [PATCH 154/162] ci: build before generating docs --- .github/workflows/release.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 60d98ba9f..516febdf7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,6 +19,12 @@ jobs: - uses: actions/checkout@v2 with: ref: ${{ github.events.inputs.tag }} + - name: Setup .NET + uses: actions/setup-dotnet@v1 + with: + dotnet-version: '6.0.x' + - name: Build project + run: dotnet build -f netstandard2.0 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - uses: nikeee/docfx-action@v1.0.0 name: Build Documentation with: From 214eec8b383b53d224ec7dce0b94dfbadfb9901e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 13:57:36 +0200 Subject: [PATCH 155/162] ci: run docs generation on windows --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 516febdf7..99bef406b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,7 +13,7 @@ on: jobs: docfx: - runs-on: ubuntu-latest + runs-on: windows-latest name: Update DocFX documentation steps: - uses: actions/checkout@v2 From b8c85b7df81aa1a49a583a0e53d77e9ae4b8136a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 14:07:05 +0200 Subject: [PATCH 156/162] ci: use choco docfx on windows --- .github/workflows/release.yml | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 99bef406b..f58a8f432 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -25,10 +25,17 @@ jobs: dotnet-version: '6.0.x' - name: Build project run: dotnet build -f netstandard2.0 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj - - uses: nikeee/docfx-action@v1.0.0 - name: Build Documentation - with: - args: docs/help/docfx.json + +# - uses: nikeee/docfx-action@v1.0.0 +# name: Build Documentation +# with: +# args: docs/help/docfx.json + + - name: Install docfx + run: choco install docfx + + - name: Build Documentation + run: docfx docs/help/docsfx.json --warningsAsErrors - uses: JamesIves/github-pages-deploy-action@3.6.2 name: Publish documentation to Github Pages From f6e1987cd514a9605597d8da489a46b747b0c860 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 14:10:34 +0200 Subject: [PATCH 157/162] ci: fix typo in config path --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f58a8f432..eb093f7a6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,7 +35,7 @@ jobs: run: choco install docfx - name: Build Documentation - run: docfx docs/help/docsfx.json --warningsAsErrors + run: docfx docs/help/docfx.json --warningsAsErrors - uses: JamesIves/github-pages-deploy-action@3.6.2 name: Publish documentation to Github Pages From 76eb6c4116037b0c5be123d5f05e77fb371d919c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 14:52:16 +0200 Subject: [PATCH 158/162] ci: split docs gen to build/deploy --- .github/workflows/release.yml | 40 ++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eb093f7a6..f1037d294 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -12,41 +12,51 @@ on: required: true jobs: - docfx: + build: runs-on: windows-latest name: Update DocFX documentation steps: - uses: actions/checkout@v2 with: ref: ${{ github.events.inputs.tag }} + - name: Setup .NET uses: actions/setup-dotnet@v1 with: dotnet-version: '6.0.x' + - name: Build project run: dotnet build -f netstandard2.0 src/ICSharpCode.SharpZipLib/ICSharpCode.SharpZipLib.csproj -# - uses: nikeee/docfx-action@v1.0.0 -# name: Build Documentation -# with: -# args: docs/help/docfx.json - - name: Install docfx run: choco install docfx - name: Build Documentation run: docfx docs/help/docfx.json --warningsAsErrors - - uses: JamesIves/github-pages-deploy-action@3.6.2 - name: Publish documentation to Github Pages - with: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - BRANCH: gh-pages - FOLDER: docs/help/_site - TARGET_FOLDER: help - CLEAN: false - - name: Upload documentation as artifact uses: actions/upload-artifact@v2 with: + name: site path: docs/help/_site + + deploy: + needs: [build] # The second job must depend on the first one to complete before running and uses ubuntu-latest instead of windows. + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Download Artifacts 🔻 # The built project is downloaded into the 'site' folder. + uses: actions/download-artifact@v1 + with: + name: site + + - name: Publish documentation to Github Pages + uses: JamesIves/github-pages-deploy-action@v4 + with: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BRANCH: gh-pages + FOLDER: site + TARGET_FOLDER: help + CLEAN: false From d2a0c68d0fceacb5519391078e988185a88c7c2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?nils=20m=C3=A5s=C3=A9n?= Date: Sun, 18 Sep 2022 15:01:25 +0200 Subject: [PATCH 159/162] ci: fix config keys for deploy --- .github/workflows/release.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f1037d294..388f7f5e9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -14,7 +14,7 @@ on: jobs: build: runs-on: windows-latest - name: Update DocFX documentation + name: Generate DocFX documentation steps: - uses: actions/checkout@v2 with: @@ -43,11 +43,12 @@ jobs: deploy: needs: [build] # The second job must depend on the first one to complete before running and uses ubuntu-latest instead of windows. runs-on: ubuntu-latest + name: Update github pages docs steps: - name: Checkout uses: actions/checkout@v3 - - name: Download Artifacts 🔻 # The built project is downloaded into the 'site' folder. + - name: Download Artifacts # The built project is downloaded into the 'site' folder. uses: actions/download-artifact@v1 with: name: site @@ -55,8 +56,8 @@ jobs: - name: Publish documentation to Github Pages uses: JamesIves/github-pages-deploy-action@v4 with: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - BRANCH: gh-pages - FOLDER: site - TARGET_FOLDER: help - CLEAN: false + token: ${{ secrets.GITHUB_TOKEN }} + branch: gh-pages + folder: site + target-folder: help + clean: false From 82c74c14579ae64a7e372009595726f21ebe08f5 Mon Sep 17 00:00:00 2001 From: Richard Webb Date: Sun, 18 Aug 2019 23:08:58 +0100 Subject: [PATCH 160/162] Add support for AES encryption --- .../Encryption/ZipAESStream.cs | 2 +- .../Encryption/ZipAESTransform.cs | 39 ++- .../Streams/InflaterInputStream.cs | 52 +++- .../Zip/ZipConstants.cs | 10 + src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs | 15 +- .../Zip/ZipInputStream.cs | 164 +++++++++--- .../Zip/ZipOutputStream.cs | 9 + .../Zip/ZipEncryptionHandling.cs | 249 +++++++++++++++--- 8 files changed, 463 insertions(+), 77 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs index 346b5484b..fbf76a77b 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESStream.cs @@ -40,7 +40,7 @@ public ZipAESStream(Stream stream, ZipAESTransform transform, CryptoStreamMode m } // The final n bytes of the AES stream contain the Auth Code. - public const int AUTH_CODE_LENGTH = 10; + public const int AUTH_CODE_LENGTH = Zip.ZipConstants.AESAuthCodeLength; // Blocksize is always 16 here, even for AES-256 which has transform.InputBlockSize of 32. private const int CRYPTO_BLOCK_SIZE = 16; diff --git a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs index 32c7b8156..9e7790dec 100644 --- a/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs +++ b/src/ICSharpCode.SharpZipLib/Encryption/ZipAESTransform.cs @@ -8,8 +8,6 @@ namespace ICSharpCode.SharpZipLib.Encryption /// internal class ZipAESTransform : ICryptoTransform { - private const int PWD_VER_LENGTH = 2; - // WinZip use iteration count of 1000 for PBKDF2 key generation private const int KEY_ROUNDS = 1000; @@ -28,6 +26,7 @@ internal class ZipAESTransform : ICryptoTransform private byte[] _authCode = null; private bool _writeMode; + private Action _appendHmac = remaining => { }; /// /// Constructor. @@ -63,12 +62,29 @@ public ZipAESTransform(string key, byte[] saltBytes, int blockSize, bool writeMo // Use empty IV for AES _encryptor = rm.CreateEncryptor(key1bytes, new byte[16]); - _pwdVerifier = pdb.GetBytes(PWD_VER_LENGTH); + _pwdVerifier = pdb.GetBytes(Zip.ZipConstants.AESPasswordVerifyLength); // _hmacsha1 = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA1, key2bytes); _writeMode = writeMode; } + /// + /// Append all of the last transformed input data to the HMAC. + /// + public void AppendAllPending() + { + _appendHmac(0); + } + + /// + /// Append all except the number of bytes specified by remaining of the last transformed input data to the HMAC. + /// + /// The number of bytes not to be added to the HMAC. The excluded bytes are form the end. + public void AppendFinal(int remaining) + { + _appendHmac(remaining); + } + /// /// Implement the ICryptoTransform method. /// @@ -78,8 +94,16 @@ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, b // This does not change the inputBuffer. Do this before decryption for read mode. if (!_writeMode) { - _hmacsha1.AppendData(inputBuffer, inputOffset, inputCount); + if (!ManualHmac) + { + _hmacsha1.AppendData(inputBuffer, inputOffset, inputCount); + } + else + { + _appendHmac = remaining => _hmacsha1.AppendData(inputBuffer, inputOffset, inputCount - remaining); + } } + // Encrypt with AES in CTR mode. Regards to Dr Brian Gladman for this. int ix = 0; while (ix < inputCount) @@ -168,6 +192,13 @@ public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int input /// public bool CanReuseTransform => true; + /// + /// Gets of sets a value indicating if the HMAC is updates on every read of if updating the HMAC has to be controlled manually + /// Manual control of HMAC is needed in case not all the Transformed data should be automatically added to the HMAC. + /// E.g. because its not know how much data belongs to the current entry before the data is decrypted and analyzed. + /// + public bool ManualHmac { get; set; } + /// /// Cleanup internal state. /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs index 7790474d2..5ce4ed26b 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs @@ -1,6 +1,7 @@ using System; using System.IO; using System.Security.Cryptography; +using ICSharpCode.SharpZipLib.Encryption; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { @@ -92,9 +93,25 @@ public byte[] ClearText public int Available { get { return available; } - set { available = value; } + set + { + if (cryptoTransform is ZipAESTransform ct) + { + ct.AppendFinal(value); + } + + available = value; + } } + /// + /// A limitation how much data is decrypted. If null all the data in the input buffer will be decrypted. + /// Setting limit is important in case the HMAC has to be calculated for each zip entry. In that case + /// it is not possible to decrypt all available data in the input buffer, and only the data + /// belonging to the current zip entry must be decrypted so that the HMAC is correctly calculated. + /// + internal int? DecryptionLimit { get; set; } + /// /// Call passing the current clear text buffer contents. /// @@ -113,6 +130,11 @@ public void SetInflaterInput(Inflater inflater) /// public void Fill() { + if (cryptoTransform is ZipAESTransform ct) + { + ct.AppendAllPending(); + } + rawLength = 0; int toRead = rawData.Length; @@ -127,13 +149,11 @@ public void Fill() toRead -= count; } + clearTextLength = rawLength; if (cryptoTransform != null) { - clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0); - } - else - { - clearTextLength = rawLength; + var size = CalculateDecryptionSize(rawLength); + cryptoTransform.TransformBlock(rawData, 0, size, clearText, 0); } available = clearTextLength; @@ -290,7 +310,9 @@ public ICryptoTransform CryptoTransform clearTextLength = rawLength; if (available > 0) { - cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available); + var size = CalculateDecryptionSize(available); + + cryptoTransform.TransformBlock(rawData, rawLength - available, size, clearText, rawLength - available); } } else @@ -301,6 +323,19 @@ public ICryptoTransform CryptoTransform } } + private int CalculateDecryptionSize(int availableBufferSize) + { + int size = DecryptionLimit ?? availableBufferSize; + size = Math.Min(size, availableBufferSize); + + if (DecryptionLimit.HasValue) + { + DecryptionLimit -= size; + } + + return size; + } + #region Instance Fields private int rawLength; @@ -459,9 +494,10 @@ public long Skip(long count) /// /// Clear any cryptographic state. /// - protected void StopDecrypting() + protected virtual void StopDecrypting() { inputBuffer.CryptoTransform = null; + inputBuffer.DecryptionLimit = null; } /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs index b16fdefdf..24643bf2a 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipConstants.cs @@ -366,6 +366,16 @@ public static class ZipConstants [Obsolete("Use CryptoHeaderSize instead")] public const int CRYPTO_HEADER_SIZE = 12; + /// + /// The number of bytes in the WinZipAes Auth Code. + /// + internal const int AESAuthCodeLength = 10; + + /// + /// The number of bytes in the password verifier for WinZipAes. + /// + internal const int AESPasswordVerifyLength = 2; + /// /// The size of the Zip64 central directory locator. /// diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs index b0bf15821..08ff6d09f 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipEntry.cs @@ -824,6 +824,19 @@ public int AESKeySize } } + /// + /// Gets the AES Version + /// 1: AE-1 + /// 2: AE-2 + /// + public int AESVersion + { + get + { + return _aesVer; + } + } + /// /// AES Encryption strength for storage in extra data in entry header. /// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit. @@ -1149,7 +1162,7 @@ public static string CleanName(string name) private bool forceZip64_; private byte cryptoCheckValue_; - private int _aesVer; // Version number (2 = AE-2 ?). Assigned but not used. + private int _aesVer; // Version number (1 = AE-1, 2 = AE-2) private int _aesEncryptionStrength; // Encryption strength 1 = 128 2 = 192 3 = 256 #endregion Instance Fields diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs index e49ebddfb..bde176788 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipInputStream.cs @@ -74,10 +74,10 @@ public class ZipInputStream : InflaterInputStream private ZipEntry entry; private long size; - private CompressionMethod method; private int flags; private string password; private readonly StringCodec _stringCodec = ZipStrings.GetStringCodec(); + private ZipAESTransform cryptoTransform; #endregion Instance Fields @@ -141,17 +141,22 @@ public bool CanDecompressEntry /// /// Is the compression method for the specified entry supported? /// - /// - /// Uses entry.CompressionMethodForHeader so that entries of type WinZipAES will be rejected. - /// /// the entry to check. /// true if the compression method is supported, false if not. private static bool IsEntryCompressionMethodSupported(ZipEntry entry) { - var entryCompressionMethod = entry.CompressionMethodForHeader; - - return entryCompressionMethod == CompressionMethod.Deflated || - entryCompressionMethod == CompressionMethod.Stored; + var entryCompressionMethodForHeader = entry.CompressionMethodForHeader; + var entryCompressionMethod = entry.CompressionMethod; + + var compressionMethodSupported = + entryCompressionMethod == CompressionMethod.Deflated || + entryCompressionMethod == CompressionMethod.Stored; + var entryCompressionMethodForHeaderSupported = + entryCompressionMethodForHeader == CompressionMethod.Deflated || + entryCompressionMethodForHeader == CompressionMethod.Stored || + entryCompressionMethodForHeader == CompressionMethod.WinZipAES; + + return compressionMethodSupported && entryCompressionMethodForHeaderSupported; } /// @@ -191,7 +196,7 @@ public ZipEntry GetNextEntry() var versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); flags = inputBuffer.ReadLeShort(); - method = (CompressionMethod)inputBuffer.ReadLeShort(); + var method = (CompressionMethod)inputBuffer.ReadLeShort(); var dostime = (uint)inputBuffer.ReadLeInt(); int crc2 = inputBuffer.ReadLeInt(); csize = inputBuffer.ReadLeInt(); @@ -267,9 +272,20 @@ public ZipEntry GetNextEntry() size = entry.Size; } - if (method == CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) + if (method == CompressionMethod.Stored) + { + if (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size)) + { + throw new ZipException("Stored, but compressed != uncompressed"); + } + } + else if (method == CompressionMethod.WinZipAES && entry.CompressionMethod == CompressionMethod.Stored) { - throw new ZipException("Stored, but compressed != uncompressed"); + var sizeWithoutAesOverhead = csize - (entry.AESSaltLen + ZipConstants.AESPasswordVerifyLength + ZipConstants.AESAuthCodeLength); + if (sizeWithoutAesOverhead != size) + { + throw new ZipException("Stored, but compressed != uncompressed"); + } } // Determine how to handle reading of data if this is attempted. @@ -359,13 +375,50 @@ private void ReadDataDescriptor() entry.Size = size; } + /// + /// Complete any decryption processing and clear any cryptographic state. + /// + private void StopDecrypting(bool testAESAuthCode) + { + StopDecrypting(); + + if (testAESAuthCode && entry.AESKeySize != 0) + { + byte[] authBytes = new byte[ZipConstants.AESAuthCodeLength]; + int authBytesRead = inputBuffer.ReadRawBuffer(authBytes, 0, authBytes.Length); + + if (authBytesRead < ZipConstants.AESAuthCodeLength) + { + throw new ZipException("Internal error missed auth code"); // Coding bug + } + + // Final block done. Check Auth code. + byte[] calcAuthCode = this.cryptoTransform.GetAuthCode(); + for (int i = 0; i < ZipConstants.AESAuthCodeLength; i++) + { + if (calcAuthCode[i] != authBytes[i]) + { + throw new ZipException("AES Authentication Code does not match. This is a super-CRC check on the data in the file after compression and encryption. The file may be damaged or tampered."); + } + } + + // Dispose the transform? + } + } + /// /// Complete cleanup as the final part of closing. /// /// True if the crc value should be tested private void CompleteCloseEntry(bool testCrc) { - StopDecrypting(); + StopDecrypting(testCrc); + + // AE-2 does not have a CRC by specification. Do not check CRC in this case. + if (entry.AESKeySize != 0 && entry.AESVersion == 2) + { + testCrc = false; + } if ((flags & 8) != 0) { @@ -382,7 +435,7 @@ private void CompleteCloseEntry(bool testCrc) crc.Reset(); - if (method == CompressionMethod.Deflated) + if (entry.CompressionMethod == CompressionMethod.Deflated) { inf.Reset(); } @@ -409,8 +462,8 @@ public void CloseEntry() { return; } - - if (method == CompressionMethod.Deflated) + + if (entry.CompressionMethod == CompressionMethod.Deflated) { if ((flags & 8) != 0) { @@ -425,6 +478,7 @@ public void CloseEntry() } csize -= inf.TotalIn; + inputBuffer.Available += inf.RemainingInput; } @@ -556,27 +610,69 @@ private int InitialRead(byte[] destination, int offset, int count) throw new ZipException("No password set."); } - // Generate and set crypto transform... - var managed = new PkzipClassicManaged(); - byte[] key = PkzipClassic.GenerateKeys(_stringCodec.ZipCryptoEncoding.GetBytes(password)); + if (entry.AESKeySize == 0) + { + // Generate and set crypto transform... + var managed = new PkzipClassicManaged(); + byte[] key = PkzipClassic.GenerateKeys(_stringCodec.ZipCryptoEncoding.GetBytes(password)); - inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); + inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); + inputBuffer.DecryptionLimit = null; - byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; - inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize); + byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; + inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize); - if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) - { - throw new ZipException("Invalid password"); - } + if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) + { + throw new ZipException("Invalid password"); + } - if (csize >= ZipConstants.CryptoHeaderSize) - { - csize -= ZipConstants.CryptoHeaderSize; + if (csize >= ZipConstants.CryptoHeaderSize) + { + csize -= ZipConstants.CryptoHeaderSize; + } + else if (!usesDescriptor) + { + throw new ZipException($"Entry compressed size {csize} too small for encryption"); + } } - else if (!usesDescriptor) + else { - throw new ZipException($"Entry compressed size {csize} too small for encryption"); + int saltLen = entry.AESSaltLen; + byte[] saltBytes = new byte[saltLen]; + int saltIn = inputBuffer.ReadRawBuffer(saltBytes, 0, saltLen); + + if (saltIn != saltLen) + { + throw new ZipException("AES Salt expected " + saltLen + " got " + saltIn); + } + + // + byte[] pwdVerifyRead = new byte[ZipConstants.AESPasswordVerifyLength]; + int pwdBytesRead = inputBuffer.ReadRawBuffer(pwdVerifyRead, 0, pwdVerifyRead.Length); + + if (pwdBytesRead != pwdVerifyRead.Length) + { + throw new EndOfStreamException(); + } + + int blockSize = entry.AESKeySize / 8; // bits to bytes + + var decryptor = new ZipAESTransform(password, saltBytes, blockSize, false); + decryptor.ManualHmac = csize <= 0; + byte[] pwdVerifyCalc = decryptor.PwdVerifier; + if (pwdVerifyCalc[0] != pwdVerifyRead[0] || pwdVerifyCalc[1] != pwdVerifyRead[1]) + { + throw new ZipException("Invalid password for AES"); + } + + // The AES data has saltLen+AESPasswordVerifyLength bytes as a header, and AESAuthCodeLength bytes + // as a footer. + csize -= (saltLen + ZipConstants.AESPasswordVerifyLength + ZipConstants.AESAuthCodeLength); + inputBuffer.DecryptionLimit = csize >= 0 ? (int?)csize : null; + + inputBuffer.CryptoTransform = decryptor; + this.cryptoTransform = decryptor; } } else @@ -586,13 +682,13 @@ private int InitialRead(byte[] destination, int offset, int count) if (csize > 0 || usesDescriptor) { - if (method == CompressionMethod.Deflated && inputBuffer.Available > 0) + if (entry.CompressionMethod == CompressionMethod.Deflated && inputBuffer.Available > 0) { inputBuffer.SetInflaterInput(inf); } // It's not possible to know how many bytes to read when using "Stored" compression (unless using encryption) - if (!entry.IsCrypted && method == CompressionMethod.Stored && usesDescriptor) + if (!entry.IsCrypted && entry.CompressionMethod == CompressionMethod.Stored && usesDescriptor) { internalReader = StoredDescriptorEntry; return StoredDescriptorEntry(destination, offset, count); @@ -680,7 +776,7 @@ private int BodyRead(byte[] buffer, int offset, int count) bool finished = false; - switch (method) + switch (entry.CompressionMethod) { case CompressionMethod.Deflated: count = base.Read(buffer, offset, count); @@ -731,6 +827,8 @@ private int BodyRead(byte[] buffer, int offset, int count) } } break; + default: + throw new InvalidOperationException("Internal Error: Unsupported compression method encountered."); } if (count > 0) diff --git a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs index 21042f75a..eaff7684d 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/ZipOutputStream.cs @@ -443,6 +443,15 @@ internal void PutNextEntry(Stream stream, ZipEntry entry, long streamOffset = 0, if (Password != null) { entry.IsCrypted = true; + + // In case of AES the CRC is always 0 according to specification. + // This also prevents that a data descriptor is needed for the CRC as it is the case for other + // password protected zip files. AES uses a 10 Byte auth code instead of the CRC + if (entry.AESKeySize != 0) + { + entry.Crc = 0; + } + if (entry.Crc < 0) { // Need to append a data descriptor as the crc isnt available for use diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index 0cf7395cb..8d98df29e 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -12,6 +12,18 @@ namespace ICSharpCode.SharpZipLib.Tests.Zip [TestFixture] public class ZipEncryptionHandling { + static ZipEncryptionHandling() + { + var sb = new StringBuilder(); + for (int i = 0; i < 200; i++) + { + sb.AppendLine(Guid.NewGuid().ToString()); + } + + DummyDataString = sb.ToString(); + DummyDataStringShort = Guid.NewGuid().ToString(); + } + [Test] [Category("Encryption")] [Category("Zip")] @@ -110,6 +122,143 @@ public void ZipFileAesDecryption() } } + /// + /// Tests for reading encrypted entries using ZipInputStream. + /// + [Test] + [Category("Encryption")] + [Category("Zip")] + public void ZipInputStreamDecryption( + [Values(0, 128, 256)] int aesKeySize, + [Values(CompressionMethod.Stored, CompressionMethod.Deflated)] + CompressionMethod compressionMethod, + [Values] bool forceDataDescriptor) + { + var password = "password"; + + using (var ms = forceDataDescriptor ? new MemoryStreamWithoutSeek() : new MemoryStream()) + { + WriteEncryptedZipToStream(ms, 3, 3, password, aesKeySize, compressionMethod); + ms.Seek(0, SeekOrigin.Begin); + + using (var zis = new ZipInputStream(ms)) + { + zis.IsStreamOwner = false; + zis.Password = password; + + for (int i = 0; i < 6; i++) + { + var entry = zis.GetNextEntry(); + int fileNumber = int.Parse(entry.Name[5].ToString()); + + using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) + { + var content = sr.ReadToEnd(); + + Assert.AreEqual(fileNumber < 3 ? DummyDataString : DummyDataStringShort, content, + "Decompressed content does not match input data"); + } + } + } + } + } + + /// + /// Tests for reading encrypted entries using ZipInputStream. + /// Verify that it is possible to skip reading of entries. + /// + [Test] + [Category("Encryption")] + [Category("Zip")] + public void ZipInputStreamDecryptionSupportsSkippingEntries( + [Values(0, 128, 256)] int aesKeySize, + [Values(CompressionMethod.Stored, CompressionMethod.Deflated)] + CompressionMethod compressionMethod, + [Values] bool forceDataDescriptor) + { + var password = "password"; + + using (var ms = forceDataDescriptor ? new MemoryStreamWithoutSeek() : new MemoryStream()) + { + WriteEncryptedZipToStream(ms, 3, 3, password, aesKeySize, compressionMethod); + ms.Seek(0, SeekOrigin.Begin); + + using (var zis = new ZipInputStream(ms)) + { + zis.IsStreamOwner = false; + zis.Password = password; + + for (int i = 0; i < 6; i++) + { + var entry = zis.GetNextEntry(); + int fileNumber = int.Parse(entry.Name[5].ToString()); + + if (fileNumber % 2 == 1) + { + continue; + } + + using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, + detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) + { + var content = sr.ReadToEnd(); + + Assert.AreEqual(fileNumber < 3 ? DummyDataString : DummyDataStringShort, content, + "Decompressed content does not match input data"); + } + } + } + } + } + + /// + /// Tests for reading encrypted entries using ZipInputStream. + /// Verify that it is possible to read entries only partially. + /// + [Test] + [Category("Encryption")] + [Category("Zip")] + public void ZipInputStreamDecryptionSupportsPartiallyReadingOfEntries( + [Values(0, 128, 256)] int aesKeySize, + [Values(CompressionMethod.Stored, CompressionMethod.Deflated)] + CompressionMethod compressionMethod, + [Values] bool forceDataDescriptor) + { + var password = "password"; + + using (var ms = forceDataDescriptor ? new MemoryStreamWithoutSeek() : new MemoryStream()) + { + WriteEncryptedZipToStream(ms, 3, 3, password, aesKeySize, compressionMethod); + ms.Seek(0, SeekOrigin.Begin); + + using (var zis = new ZipInputStream(ms)) + { + zis.IsStreamOwner = false; + zis.Password = password; + + for (int i = 0; i < 6; i++) + { + var entry = zis.GetNextEntry(); + int fileNumber = int.Parse(entry.Name[5].ToString()); + + if (fileNumber % 2 == 1) + { + zis.ReadByte(); + continue; + } + + using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) + { + var content = sr.ReadToEnd(); + + Assert.AreEqual(fileNumber < 3 ? DummyDataString : DummyDataStringShort, content, + "Decompressed content does not match input data"); + } + } + } + } + } + [Test] [Category("Encryption")] [Category("Zip")] @@ -379,7 +528,7 @@ public void ZipFileAesDelete() using (var memoryStream = new MemoryStream()) { // Try to create a zip stream - WriteEncryptedZipToStream(memoryStream, 3, password, keySize, CompressionMethod.Deflated); + WriteEncryptedZipToStream(memoryStream, 3, 0, password, keySize, CompressionMethod.Deflated); // reset memoryStream.Seek(0, SeekOrigin.Begin); @@ -482,40 +631,77 @@ public void ZipFileAESReadWithEmptyPassword() } } } + + // This is a zip file with three AES encrypted entry, whose password is password. + const string TestFileWithThreeEntries = @"UEsDBDMAAQBjAI9jbFIAAAAAIQAAAAUAAAAJAAsARmlsZTEudHh0AZkHAAIAQUUDAAAoyz4gbB4/SnNvoPSBMVS9Zhp5sKKD + GnLy8zwsuV0Jh/RQSwMEMwABAGMAnWNsUgAAAAAhAAAABQAAAAkACwBGaWxlMi50eHQBmQcAAgBBRQMAANoCDbQUG7iCJgGC2/5OrmUQUk/+fACL804W0bboF8YMM1BLAwQzAA + EAYwCjY2xSAAAAACEAAAAFAAAACQALAEZpbGUzLnR4dAGZBwACAEFFAwAAqmBqgBkl3tP6ND0uCD50mhwfOtbmwV1IKyUVK5wGVQUiUEsBAj8AMwABAGMAj2NsUgAAAAAhAAAA + BQAAAAkALwAAAAAAAAAgAAAAAAAAAEZpbGUxLnR4dAoAIAAAAAAAAQAYAApFb9MyF9cB7fEh1jIX1wHNrjnNMhfXAQGZBwACAEFFAwAAUEsBAj8AMwABAGMAnWNsUgAAAAAhAA + AABQAAAAkALwAAAAAAAAAgAAAAUwAAAEZpbGUyLnR4dAoAIAAAAAAAAQAYAK5pWOQyF9cBdTCL5TIX1wGab3HVMhfXAQGZBwACAEFFAwAAUEsBAj8AMwABAGMAo2NsUgAAAAAh + AAAABQAAAAkALwAAAAAAAAAgAAAApgAAAEZpbGUzLnR4dAoAIAAAAAAAAQAYANB1M+kyF9cB0gxl6jIX1wGqVSHWMhfXAQGZBwACAEFFAwAAUEsFBgAAAAADAAMAMgEAAPkAAAAAAA=="; /// - /// ZipInputStream can't decrypt AES encrypted entries, but it should report that to the caller - /// rather than just failing. + /// Test reading an AES encrypted file and skipping some entries by not reading form the stream /// [Test] [Category("Zip")] - public void ZipinputStreamShouldGracefullyFailWithAESStreams() + public void ZipInputStreamAESReadSkippingEntriesIsPossible() { - string password = "password"; + var fileBytes = Convert.FromBase64String(TestFileWithThreeEntries); - using (var memoryStream = new MemoryStream()) + using (var ms = new MemoryStream(fileBytes)) + using (var zis = new ZipInputStream(ms) { IsStreamOwner = false}) { - // Try to create a zip stream - WriteEncryptedZipToStream(memoryStream, password, 256); + zis.Password = "password"; - // reset - memoryStream.Seek(0, SeekOrigin.Begin); - - // Try to read - using (var inputStream = new ZipInputStream(memoryStream)) + for (int i = 0; i < 3; i++) { - inputStream.Password = password; - var entry = inputStream.GetNextEntry(); - Assert.That(entry.AESKeySize, Is.EqualTo(256), "Test entry should be AES256 encrypted."); - - // CanDecompressEntry should be false. - Assert.That(inputStream.CanDecompressEntry, Is.False, "CanDecompressEntry should be false for AES encrypted entries"); + var entry = zis.GetNextEntry(); + if (i == 1) + { + continue; + } - // Should throw on read. - Assert.Throws(() => inputStream.ReadByte()); + using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) + { + var content = sr.ReadToEnd(); + Assert.AreEqual(Path.GetFileNameWithoutExtension(entry.Name), content, "Decompressed content does not match input data"); + } } } } + + /// + /// Test reading an AES encrypted file and reading some entries only partially be not reading to the end of stream. + /// + [Test] + [Category("Zip")] + public void ZipInputStreamAESReadEntriesCanBeReadPartially() + { + var fileBytes = Convert.FromBase64String(TestFileWithThreeEntries); + + using (var ms = new MemoryStream(fileBytes)) + using (var zis = new ZipInputStream(ms) { IsStreamOwner = false}) + { + zis.Password = "password"; + + for (int i = 0; i < 3; i++) + { + var entry = zis.GetNextEntry(); + if (i == 1) + { + zis.ReadByte(); + continue; + } + + using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) + { + var content = sr.ReadToEnd(); + Assert.AreEqual(Path.GetFileNameWithoutExtension(entry.Name), content, "Decompressed content does not match input data"); + } + } + } + } public static void WriteEncryptedZipToStream(Stream stream, string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated) { @@ -525,11 +711,11 @@ public static void WriteEncryptedZipToStream(Stream stream, string password, int zs.SetLevel(9); // 0-9, 9 being the highest level of compression zs.Password = password; // optional. Null is the same as not setting. Required if using AES. - AddEncrypedEntryToStream(zs, $"test", keySize, compressionMethod); + AddEncrypedEntryToStream(zs, $"test", keySize, compressionMethod, DummyDataString); } } - public void WriteEncryptedZipToStream(Stream stream, int entryCount, string password, int keySize, CompressionMethod compressionMethod) + public static void WriteEncryptedZipToStream(Stream stream, int entryCount, int shortEntryCount, string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated) { using (var zs = new ZipOutputStream(stream)) { @@ -539,12 +725,17 @@ public void WriteEncryptedZipToStream(Stream stream, int entryCount, string pass for (int i = 0; i < entryCount; i++) { - AddEncrypedEntryToStream(zs, $"test-{i}", keySize, compressionMethod); + AddEncrypedEntryToStream(zs, $"test-{i}", keySize, compressionMethod, DummyDataString); } + + for (int i = 0; i < shortEntryCount; i++) + { + AddEncrypedEntryToStream(zs, $"test-{i + entryCount}", keySize, compressionMethod, DummyDataStringShort); + } } } - private static void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod) + private static void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod, string content) { ZipEntry zipEntry = new ZipEntry(entryName) { @@ -555,7 +746,7 @@ private static void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, st zipOutputStream.PutNextEntry(zipEntry); - byte[] dummyData = Encoding.UTF8.GetBytes(DummyDataString); + byte[] dummyData = Encoding.UTF8.GetBytes(content); using (var dummyStream = new MemoryStream(dummyData)) { @@ -574,9 +765,7 @@ public void CreateZipWithEncryptedEntries(string password, int keySize, Compress } } - private const string DummyDataString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit. -Fusce bibendum diam ac nunc rutrum ornare. Maecenas blandit elit ligula, eget suscipit lectus rutrum eu. -Maecenas aliquam, purus mattis pulvinar pharetra, nunc orci maximus justo, sed facilisis massa dui sed lorem. -Vestibulum id iaculis leo. Duis porta ante lorem. Duis condimentum enim nec lorem tristique interdum. Fusce in faucibus libero."; + private static readonly string DummyDataString; + private static readonly string DummyDataStringShort; } } From 5dd930e2d7086ff042083c2328352e803521d884 Mon Sep 17 00:00:00 2001 From: Remo Gloor Date: Tue, 18 Oct 2022 13:30:55 +0200 Subject: [PATCH 161/162] Apply code refactoring suggested in review --- .../Zip/Compression/Streams/InflaterInputStream.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs index 5ce4ed26b..5c304927a 100644 --- a/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs +++ b/src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/InflaterInputStream.cs @@ -325,13 +325,13 @@ public ICryptoTransform CryptoTransform private int CalculateDecryptionSize(int availableBufferSize) { - int size = DecryptionLimit ?? availableBufferSize; - size = Math.Min(size, availableBufferSize); - - if (DecryptionLimit.HasValue) + if (!DecryptionLimit.HasValue) { - DecryptionLimit -= size; + return availableBufferSize; } + + var size = Math.Min(DecryptionLimit.Value, availableBufferSize); + DecryptionLimit -= size; return size; } From ba5296b0b6f521b434fbbb6d25204a52970d5261 Mon Sep 17 00:00:00 2001 From: Remo Gloor Date: Tue, 18 Oct 2022 14:04:58 +0200 Subject: [PATCH 162/162] Make it more explicit how big Large dummy data and small dummy data has to be. --- .../Zip/ZipEncryptionHandling.cs | 134 ++++++++---------- 1 file changed, 63 insertions(+), 71 deletions(-) diff --git a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs index 8d98df29e..0988089ee 100644 --- a/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs +++ b/test/ICSharpCode.SharpZipLib.Tests/Zip/ZipEncryptionHandling.cs @@ -5,6 +5,7 @@ using System.Text; using ICSharpCode.SharpZipLib.Tests.TestSupport; using System.Threading.Tasks; +using ICSharpCode.SharpZipLib.Core; using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does; namespace ICSharpCode.SharpZipLib.Tests.Zip @@ -12,6 +13,13 @@ namespace ICSharpCode.SharpZipLib.Tests.Zip [TestFixture] public class ZipEncryptionHandling { + static int BufferSize = 4096; + // Random data that is smaller than the size of the read buffer + private static readonly byte[] SmallDummyData = new byte[BufferSize / 2 - 41]; + + // Random data that is smaller than the size of the read buffer + private static readonly byte[] LargeDummyData = new byte[BufferSize * 3 + 245]; + static ZipEncryptionHandling() { var sb = new StringBuilder(); @@ -20,8 +28,9 @@ static ZipEncryptionHandling() sb.AppendLine(Guid.NewGuid().ToString()); } - DummyDataString = sb.ToString(); - DummyDataStringShort = Guid.NewGuid().ToString(); + var random = new Random(); + random.NextBytes(SmallDummyData); + random.NextBytes(LargeDummyData); } [Test] @@ -110,12 +119,9 @@ public void ZipFileAesDecryption() { if (!entry.IsFile) continue; - using (var zis = zipFile.GetInputStream(entry)) - using (var sr = new StreamReader(zis, Encoding.UTF8)) - { - var content = sr.ReadToEnd(); - Assert.AreEqual(DummyDataString, content, "Decompressed content does not match input data"); - } + using var zis = zipFile.GetInputStream(entry); + var content = ReadAllBytes(zis); + Assert.AreEqual(LargeDummyData, content, "Decompressed content does not match input data"); } Assert.That(zipFile, Does.PassTestArchive(testData: false), "Encrypted archive should pass validation."); @@ -151,14 +157,11 @@ public void ZipInputStreamDecryption( var entry = zis.GetNextEntry(); int fileNumber = int.Parse(entry.Name[5].ToString()); - using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) - { - var content = sr.ReadToEnd(); + var content = ReadAllBytes(zis); + var largeDataExpected = fileNumber < 3; - Assert.AreEqual(fileNumber < 3 ? DummyDataString : DummyDataStringShort, content, - "Decompressed content does not match input data"); - } - } + Assert.AreEqual(largeDataExpected ? LargeDummyData : SmallDummyData, content, + "Decompressed content does not match input data"); } } } } @@ -198,14 +201,11 @@ public void ZipInputStreamDecryptionSupportsSkippingEntries( continue; } - using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, - detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) - { - var content = sr.ReadToEnd(); + var content = ReadAllBytes(zis); + var largeDataExpected = fileNumber < 3; - Assert.AreEqual(fileNumber < 3 ? DummyDataString : DummyDataStringShort, content, - "Decompressed content does not match input data"); - } + Assert.AreEqual(largeDataExpected ? LargeDummyData : SmallDummyData, content, + "Decompressed content does not match input data"); } } } @@ -247,13 +247,11 @@ public void ZipInputStreamDecryptionSupportsPartiallyReadingOfEntries( continue; } - using (var sr = new StreamReader(zis, Encoding.UTF8, leaveOpen: true, detectEncodingFromByteOrderMarks: true, bufferSize: 1024)) - { - var content = sr.ReadToEnd(); + var content = ReadAllBytes(zis); + var largeDataExpected = fileNumber < 3; - Assert.AreEqual(fileNumber < 3 ? DummyDataString : DummyDataStringShort, content, - "Decompressed content does not match input data"); - } + Assert.AreEqual(largeDataExpected ? LargeDummyData : SmallDummyData, content, + "Decompressed content does not match input data"); } } } @@ -280,12 +278,10 @@ public void ZipFileAesRead() { if (!entry.IsFile) continue; - using (var zis = zipFile.GetInputStream(entry)) - using (var sr = new StreamReader(zis, Encoding.UTF8)) - { - var content = sr.ReadToEnd(); - Assert.AreEqual(DummyDataString, content, "Decompressed content does not match input data"); - } + using var zis = zipFile.GetInputStream(entry); + var content = ReadAllBytes(zis); + + Assert.AreEqual(LargeDummyData, content, "Decompressed content does not match input data"); } } } @@ -316,12 +312,10 @@ public void ZipFileStoreAes() // Should be stored rather than deflated Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.Stored), "Entry should be stored"); - using (var zis = zipFile.GetInputStream(entry)) - using (var sr = new StreamReader(zis, Encoding.UTF8)) - { - var content = sr.ReadToEnd(); - Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data"); - } + using var zis = zipFile.GetInputStream(entry); + var content = ReadAllBytes(zis); + + Assert.AreEqual(LargeDummyData, content, "Decompressed content does not match input data"); } } } @@ -352,12 +346,10 @@ public async Task ZipFileStoreAesAsync() using (var zis = zipFile.GetInputStream(entry)) { - using (var inputStream = zipFile.GetInputStream(entry)) - using (var sr = new StreamReader(zis, Encoding.UTF8)) - { - var content = await sr.ReadToEndAsync(); - Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data"); - } + using var inputStream = zipFile.GetInputStream(entry); + var content = ReadAllBytes(inputStream); + + Assert.That(content, Is.EqualTo(LargeDummyData), "Decompressed content does not match input data"); } } } @@ -427,11 +419,9 @@ public void ZipFileStoreAesPartialRead([Values(1, 7, 17)] int readSize) ms.Seek(0, SeekOrigin.Begin); - using (var sr = new StreamReader(ms, Encoding.UTF8)) - { - var content = sr.ReadToEnd(); - Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data"); - } + var content = ms.ToArray(); + + Assert.That(content, Is.EqualTo(LargeDummyData), "Decompressed content does not match input data"); } } } @@ -485,12 +475,10 @@ public void ZipFileAesAdd() Assert.That(originalEntry.AESKeySize, Is.EqualTo(keySize)); - using (var zis = zipFile.GetInputStream(originalEntry)) - using (var sr = new StreamReader(zis, Encoding.UTF8)) - { - var content = sr.ReadToEnd(); - Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data"); - } + using var zis = zipFile.GetInputStream(originalEntry); + var content = ReadAllBytes(zis); + + Assert.That(content, Is.EqualTo(LargeDummyData), "Decompressed content does not match input data"); } // Check the additional entry @@ -571,8 +559,9 @@ public void ZipFileAesDelete() using (var zis = zipFile.GetInputStream(originalEntry)) using (var sr = new StreamReader(zis, Encoding.UTF8)) { - var content = sr.ReadToEnd(); - Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data"); + var content = ReadAllBytes(zis); + + Assert.That(content, Is.EqualTo(LargeDummyData), "Decompressed content does not match input data"); } } @@ -586,8 +575,9 @@ public void ZipFileAesDelete() using (var zis = zipFile.GetInputStream(originalEntry)) using (var sr = new StreamReader(zis, Encoding.UTF8)) { - var content = sr.ReadToEnd(); - Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data"); + var content = ReadAllBytes(zis); + + Assert.That(content, Is.EqualTo(LargeDummyData), "Decompressed content does not match input data"); } } } @@ -711,7 +701,7 @@ public static void WriteEncryptedZipToStream(Stream stream, string password, int zs.SetLevel(9); // 0-9, 9 being the highest level of compression zs.Password = password; // optional. Null is the same as not setting. Required if using AES. - AddEncrypedEntryToStream(zs, $"test", keySize, compressionMethod, DummyDataString); + AddEncrypedEntryToStream(zs, $"test", keySize, compressionMethod, LargeDummyData); } } @@ -725,17 +715,17 @@ public static void WriteEncryptedZipToStream(Stream stream, int entryCount, int for (int i = 0; i < entryCount; i++) { - AddEncrypedEntryToStream(zs, $"test-{i}", keySize, compressionMethod, DummyDataString); + AddEncrypedEntryToStream(zs, $"test-{i}", keySize, compressionMethod, LargeDummyData); } for (int i = 0; i < shortEntryCount; i++) { - AddEncrypedEntryToStream(zs, $"test-{i + entryCount}", keySize, compressionMethod, DummyDataStringShort); + AddEncrypedEntryToStream(zs, $"test-{i + entryCount}", keySize, compressionMethod, SmallDummyData); } } } - private static void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod, string content) + private static void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod, byte[] content) { ZipEntry zipEntry = new ZipEntry(entryName) { @@ -746,9 +736,7 @@ private static void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, st zipOutputStream.PutNextEntry(zipEntry); - byte[] dummyData = Encoding.UTF8.GetBytes(content); - - using (var dummyStream = new MemoryStream(dummyData)) + using (var dummyStream = new MemoryStream(content)) { dummyStream.CopyTo(zipOutputStream); } @@ -764,8 +752,12 @@ public void CreateZipWithEncryptedEntries(string password, int keySize, Compress SevenZipHelper.VerifyZipWith7Zip(ms, password); } } - - private static readonly string DummyDataString; - private static readonly string DummyDataStringShort; + + private static byte[] ReadAllBytes(Stream input) + { + using MemoryStream ms = new MemoryStream(); + input.CopyTo(ms); + return ms.ToArray(); + } } }