-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathGeneralHandling.cs
More file actions
884 lines (758 loc) · 23.8 KB
/
GeneralHandling.cs
File metadata and controls
884 lines (758 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
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;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Text;
using Does = ICSharpCode.SharpZipLib.Tests.TestSupport.Does;
namespace ICSharpCode.SharpZipLib.Tests.Zip
{
/// <summary>
/// This class contains test cases for Zip compression and decompression
/// </summary>
[TestFixture]
public class GeneralHandling : ZipBase
{
private void ExerciseZip(CompressionMethod method, int compressionLevel,
int size, string password, bool canSeek)
{
byte[] originalData = null;
byte[] compressedData = MakeInMemoryZip(ref originalData, method, compressionLevel, size, password, canSeek);
var ms = new MemoryStream(compressedData);
ms.Seek(0, SeekOrigin.Begin);
using (ZipInputStream inStream = new ZipInputStream(ms))
{
byte[] decompressedData = new byte[size];
if (password != null)
{
inStream.Password = password;
}
ZipEntry entry2 = inStream.GetNextEntry();
if ((entry2.Flags & 8) == 0)
{
Assert.AreEqual(size, entry2.Size, "Entry size invalid");
}
int currentIndex = 0;
if (size > 0)
{
int count = decompressedData.Length;
while (true)
{
int numRead = inStream.Read(decompressedData, currentIndex, count);
if (numRead <= 0)
{
break;
}
currentIndex += numRead;
count -= numRead;
}
}
Assert.AreEqual(currentIndex, size, "Original and decompressed data different sizes");
if (originalData != null)
{
for (int i = 0; i < originalData.Length; ++i)
{
Assert.AreEqual(decompressedData[i], originalData[i], "Decompressed data doesnt match original, compression level: " + compressionLevel);
}
}
}
}
/// <summary>
/// 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)
/// </summary>
[Test]
[Category("Zip")]
[Retry(2)]
public void InvalidPasswordSeekable()
{
byte[] originalData = null;
byte[] compressedData = MakeInMemoryZip(ref originalData, CompressionMethod.Deflated, 3, 500, "Hola", true);
var ms = new MemoryStream(compressedData);
ms.Seek(0, SeekOrigin.Begin);
byte[] buf2 = new byte[originalData.Length];
int pos = 0;
var inStream = new ZipInputStream(ms);
inStream.Password = "redhead";
ZipEntry entry2 = inStream.GetNextEntry();
Assert.Throws<ZipException>(() =>
{
while (true)
{
int numRead = inStream.Read(buf2, pos, buf2.Length);
if (numRead <= 0)
{
break;
}
pos += numRead;
}
});
}
/// <summary>
/// Check that GetNextEntry can handle the situation where part of the entry data has been read
/// before the call is made. ZipInputStream.CloseEntry wasnt handling this at all.
/// </summary>
[Test]
[Category("Zip")]
public void ExerciseGetNextEntry()
{
byte[] compressedData = MakeInMemoryZip(
true,
new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true),
new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true),
new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true),
new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true),
new RuntimeInfo(null, true),
new RuntimeInfo(CompressionMethod.Stored, 2, 50, null, true),
new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true)
);
var ms = new MemoryStream(compressedData);
ms.Seek(0, SeekOrigin.Begin);
using (ZipInputStream inStream = new ZipInputStream(ms))
{
byte[] buffer = new byte[10];
while (inStream.GetNextEntry() != null)
{
// Read a portion of the data, so GetNextEntry has some work to do.
inStream.Read(buffer, 0, 10);
}
}
}
/// <summary>
/// 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)
/// </summary>
[Test]
[Category("Zip")]
[Retry(2)]
public void InvalidPasswordNonSeekable()
{
byte[] originalData = null;
byte[] compressedData = MakeInMemoryZip(ref originalData, CompressionMethod.Deflated, 3, 500, "Hola", false);
var ms = new MemoryStream(compressedData);
ms.Seek(0, SeekOrigin.Begin);
byte[] buf2 = new byte[originalData.Length];
int pos = 0;
var inStream = new ZipInputStream(ms);
inStream.Password = "redhead";
ZipEntry entry2 = inStream.GetNextEntry();
Assert.Throws<ZipException>(() =>
{
while (true)
{
int numRead = inStream.Read(buf2, pos, buf2.Length);
if (numRead <= 0)
{
break;
}
pos += numRead;
}
});
}
/// <summary>
/// Adding an entry after the stream has Finished should fail
/// </summary>
[Test]
[Category("Zip")]
//[ExpectedException(typeof(InvalidOperationException))]
public void AddEntryAfterFinish()
{
var ms = new MemoryStream();
var s = new ZipOutputStream(ms);
s.Finish();
//s.PutNextEntry(new ZipEntry("dummyfile.tst"));
Assert.That(() => s.PutNextEntry(new ZipEntry("dummyfile.tst")),
Throws.TypeOf<InvalidOperationException>());
}
/// <summary>
/// Test setting file commment to a value that is too long
/// </summary>
[Test]
[Category("Zip")]
//[ExpectedException(typeof(ArgumentOutOfRangeException))]
public void SetCommentOversize()
{
var ms = new MemoryStream();
var s = new ZipOutputStream(ms);
//s.SetComment(new String('A', 65536));
Assert.That(() => s.SetComment(new String('A', 65536)),
Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Check that simply closing ZipOutputStream finishes the zip correctly
/// </summary>
[Test]
[Category("Zip")]
public void CloseOnlyHandled()
{
var ms = new MemoryStream();
var s = new ZipOutputStream(ms);
s.PutNextEntry(new ZipEntry("dummyfile.tst"));
s.Close();
Assert.IsTrue(s.IsFinished, "Output stream should be finished");
}
/// <summary>
/// Basic compress/decompress test, no encryption, size is important here as its big enough
/// to force multiple write to output which was a problem...
/// </summary>
[Test]
[Category("Zip")]
public void BasicDeflated()
{
for (int i = 0; i <= 9; ++i)
{
ExerciseZip(CompressionMethod.Deflated, i, 50000, null, true);
}
}
/// <summary>
/// Basic compress/decompress test, no encryption, size is important here as its big enough
/// to force multiple write to output which was a problem...
/// </summary>
[Test]
[Category("Zip")]
public void BasicDeflatedNonSeekable()
{
for (int i = 0; i <= 9; ++i)
{
ExerciseZip(CompressionMethod.Deflated, i, 50000, null, false);
}
}
/// <summary>
/// Basic stored file test, no encryption.
/// </summary>
[Test]
[Category("Zip")]
public void BasicStored()
{
ExerciseZip(CompressionMethod.Stored, 0, 50000, null, true);
}
/// <summary>
/// Basic stored file test, no encryption, non seekable output
/// NOTE this gets converted to deflate level 0
/// </summary>
[Test]
[Category("Zip")]
public void BasicStoredNonSeekable()
{
ExerciseZip(CompressionMethod.Stored, 0, 50000, null, false);
}
[Test]
[Category("Zip")]
[TestCase(21348, null)]
[TestCase(24692, "Mabutu")]
public void StoredNonSeekableKnownSizeNoCrc(int targetSize, string password)
{
// This cannot be stored directly as the crc is not known.
MemoryStream ms = new MemoryStreamWithoutSeek();
using (ZipOutputStream outStream = new ZipOutputStream(ms))
{
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;
outStream.PutNextEntry(entry);
Assert.AreEqual(CompressionMethod.Deflated, entry.CompressionMethod, "Entry should be deflated");
Assert.AreEqual(-1, entry.CompressedSize, "Compressed size should be known");
byte[] original = Utils.GetDummyBytes(targetSize);
// Although this could be written in one chunk doing it in lumps
// throws up buffering problems including with encryption the original
// source for this change.
int index = 0, size = targetSize;
while (size > 0)
{
int count = (size > 0x200) ? 0x200 : size;
outStream.Write(original, index, count);
size -= 0x200;
index += count;
}
}
Assert.That(ms.ToArray(), Does.PassTestArchive(password));
}
/// <summary>
/// Basic compress/decompress test, with encryption, size is important here as its big enough
/// to force multiple writes to output which was a problem...
/// </summary>
[Test]
[Category("Zip")]
public void BasicDeflatedEncrypted()
{
for (int i = 0; i <= 9; ++i)
{
ExerciseZip(CompressionMethod.Deflated, i, 50157, "Rosebud", true);
}
}
/// <summary>
/// Basic compress/decompress test, with encryption, size is important here as its big enough
/// to force multiple write to output which was a problem...
/// </summary>
[Test]
[Category("Zip")]
public void BasicDeflatedEncryptedNonSeekable()
{
for (int i = 0; i <= 9; ++i)
{
ExerciseZip(CompressionMethod.Deflated, i, 50000, "Rosebud", false);
}
}
[Test]
[Category("Zip")]
public void SkipEncryptedEntriesWithoutSettingPassword()
{
byte[] compressedData = MakeInMemoryZip(true,
new RuntimeInfo("1234", true),
new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true),
new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true),
new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true),
new RuntimeInfo(null, true),
new RuntimeInfo(CompressionMethod.Stored, 2, 1, "4321", true),
new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true)
);
var ms = new MemoryStream(compressedData);
var inStream = new ZipInputStream(ms);
while (inStream.GetNextEntry() != null)
{
}
inStream.Close();
}
[Test]
[Category("Zip")]
public void MixedEncryptedAndPlain()
{
byte[] compressedData = MakeInMemoryZip(true,
new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true),
new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", false),
new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, false),
new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true)
);
var ms = new MemoryStream(compressedData);
using (ZipInputStream inStream = new ZipInputStream(ms))
{
inStream.Password = "1234";
int extractCount = 0;
int extractIndex = 0;
byte[] decompressedData = new byte[100];
while (inStream.GetNextEntry() != null)
{
extractCount = decompressedData.Length;
extractIndex = 0;
while (true)
{
int numRead = inStream.Read(decompressedData, extractIndex, extractCount);
if (numRead <= 0)
{
break;
}
extractIndex += numRead;
extractCount -= numRead;
}
}
inStream.Close();
}
}
/// <summary>
/// Basic stored file test, with encryption.
/// </summary>
[Test]
[Category("Zip")]
public void BasicStoredEncrypted()
{
ExerciseZip(CompressionMethod.Stored, compressionLevel: 0, size: 50000, "Rosebud", canSeek: true);
}
/// <summary>
/// Basic stored file test, with encryption, non seekable output.
/// NOTE this gets converted deflate level 0
/// </summary>
[Test]
[Category("Zip")]
public void BasicStoredEncryptedNonSeekable()
{
ExerciseZip(CompressionMethod.Stored, compressionLevel: 0, size: 50000, "Rosebud", canSeek: false);
}
/// <summary>
/// Check that when the output stream cannot seek that requests for stored
/// are in fact converted to defalted level 0
/// </summary>
[Test]
[Category("Zip")]
public void StoredNonSeekableConvertToDeflate()
{
var ms = new MemoryStreamWithoutSeek();
var outStream = new ZipOutputStream(ms);
outStream.SetLevel(8);
Assert.AreEqual(8, outStream.GetLevel(), "Compression level invalid");
var entry = new ZipEntry("1.tst");
entry.CompressionMethod = CompressionMethod.Stored;
outStream.PutNextEntry(entry);
Assert.AreEqual(0, outStream.GetLevel(), "Compression level invalid");
Utils.WriteDummyData(outStream, 100);
entry = new ZipEntry("2.tst");
entry.CompressionMethod = CompressionMethod.Deflated;
outStream.PutNextEntry(entry);
Assert.AreEqual(8, outStream.GetLevel(), "Compression level invalid");
Utils.WriteDummyData(outStream, 100);
outStream.Close();
}
/// <summary>
/// Check that adding more than the 2.0 limit for entry numbers is detected and handled
/// </summary>
//[Test]
//[Category("Zip")]
//[Category("Long Running")]
//public void Stream_64KPlusOneEntries()
//{
// const int target = 65537;
// MemoryStream ms = new MemoryStream();
// using (ZipOutputStream s = new ZipOutputStream(ms)) {
// for (int i = 0; i < target; ++i) {
// s.PutNextEntry(new ZipEntry("dummyfile.tst"));
// }
// s.Finish();
// ms.Seek(0, SeekOrigin.Begin);
// using (ZipFile zipFile = new ZipFile(ms)) {
// Assert.AreEqual(target, zipFile.Count, "Incorrect number of entries stored");
// }
// }
//}
/// <summary>
/// Check that Unicode filename support works.
/// </summary>
[Test]
[Category("Zip")]
public void Stream_UnicodeEntries()
{
var ms = new MemoryStream();
using (ZipOutputStream s = new ZipOutputStream(ms))
{
s.IsStreamOwner = false;
string sampleName = "\u03A5\u03d5\u03a3";
var sample = new ZipEntry(sampleName);
sample.IsUnicodeText = true;
s.PutNextEntry(sample);
s.Finish();
ms.Seek(0, SeekOrigin.Begin);
using (ZipInputStream zis = new ZipInputStream(ms))
{
ZipEntry ze = zis.GetNextEntry();
Assert.AreEqual(sampleName, ze.Name, "Expected name to match original");
Assert.IsTrue(ze.IsUnicodeText, "Expected IsUnicodeText flag to be set");
}
}
}
[Test]
[Category("Zip")]
[Category("CreatesTempFile")]
public void PartialStreamClosing()
{
string tempFile = GetTempFilePath();
Assert.IsNotNull(tempFile, "No permission to execute this test?");
if (tempFile != null)
{
tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
MakeZipFile(tempFile, new String[] { "Farriera", "Champagne", "Urban myth" }, 10, "Aha");
using (ZipFile zipFile = new ZipFile(tempFile))
{
Stream stream = zipFile.GetInputStream(0);
stream.Close();
stream = zipFile.GetInputStream(1);
zipFile.Close();
}
File.Delete(tempFile);
}
}
private void TestLargeZip(string tempFile, int targetFiles)
{
const int BlockSize = 4096;
byte[] data = new byte[BlockSize];
byte nextValue = 0;
for (int i = 0; i < BlockSize; ++i)
{
nextValue = ScatterValue(nextValue);
data[i] = nextValue;
}
using (ZipFile zFile = new ZipFile(tempFile))
{
Assert.AreEqual(targetFiles, zFile.Count);
byte[] readData = new byte[BlockSize];
int readIndex;
foreach (ZipEntry ze in zFile)
{
Stream s = zFile.GetInputStream(ze);
readIndex = 0;
while (readIndex < readData.Length)
{
readIndex += s.Read(readData, readIndex, data.Length - readIndex);
}
for (int ii = 0; ii < BlockSize; ++ii)
{
Assert.AreEqual(data[ii], readData[ii]);
}
}
zFile.Close();
}
}
// [Test]
// [Category("Zip")]
// [Category("CreatesTempFile")]
public void TestLargeZipFile()
{
string tempFile = @"g:\\tmp";
tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
TestLargeZip(tempFile, 8100);
}
// [Test]
// [Category("Zip")]
// [Category("CreatesTempFile")]
public void MakeLargeZipFile()
{
string tempFile = null;
try
{
// tempFile = Path.GetTempPath();
tempFile = @"g:\\tmp";
}
catch (SecurityException)
{
}
Assert.IsNotNull(tempFile, "No permission to execute this test?");
const int blockSize = 4096;
byte[] data = new byte[blockSize];
byte nextValue = 0;
for (int i = 0; i < blockSize; ++i)
{
nextValue = ScatterValue(nextValue);
data[i] = nextValue;
}
tempFile = Path.Combine(tempFile, "SharpZipTest.Zip");
Console.WriteLine("Starting at {0}", DateTime.Now);
try
{
// MakeZipFile(tempFile, new String[] {"1", "2" }, int.MaxValue, "C1");
using (FileStream fs = File.Create(tempFile))
{
var zOut = new ZipOutputStream(fs);
zOut.SetLevel(4);
const int TargetFiles = 8100;
for (int i = 0; i < TargetFiles; ++i)
{
var e = new ZipEntry(i.ToString());
e.CompressionMethod = CompressionMethod.Stored;
zOut.PutNextEntry(e);
for (int block = 0; block < 128; ++block)
{
zOut.Write(data, 0, blockSize);
}
}
zOut.Close();
fs.Close();
TestLargeZip(tempFile, TargetFiles);
}
}
finally
{
Console.WriteLine("Starting at {0}", DateTime.Now);
// File.Delete(tempFile);
}
}
/// <summary>
/// Test for handling of zero lengths in compression using a formatter which
/// will request reads of zero length...
/// </summary>
[Test]
[Category("Zip")]
[Ignore("With ArraySegment<byte> for crc checking, this test doesn't throw an exception. Not sure if it's needed.")]
public void SerializedObjectZeroLength()
{
bool exception = false;
object data = new byte[0];
// Thisa wont be zero length here due to serialisation.
try
{
byte[] zipped = ZipZeroLength(data);
object o = UnZipZeroLength(zipped);
var returned = o as byte[];
Assert.IsNotNull(returned, "Expected a byte[]");
Assert.AreEqual(0, returned.Length);
}
catch (ArgumentOutOfRangeException)
{
exception = true;
}
Assert.IsTrue(exception, "Passing an offset greater than or equal to buffer.Length should cause an ArgumentOutOfRangeException");
}
/// <summary>
/// Test for handling of serialized reference and value objects.
/// </summary>
[Test]
[Category("Zip")]
public void SerializedObject()
{
var sampleDateTime = new DateTime(1853, 8, 26);
var data = (object)sampleDateTime;
byte[] zipped = ZipZeroLength(data);
object rawObject = UnZipZeroLength(zipped);
var returnedDateTime = (DateTime)rawObject;
Assert.AreEqual(sampleDateTime, returnedDateTime);
string sampleString = "Mary had a giant cat it ears were green and smelly";
zipped = ZipZeroLength(sampleString);
rawObject = UnZipZeroLength(zipped);
var returnedString = rawObject as string;
Assert.AreEqual(sampleString, returnedString);
}
private byte[] ZipZeroLength(object data)
{
var formatter = new BinaryFormatter();
var memStream = new MemoryStream();
using (ZipOutputStream zipStream = new ZipOutputStream(memStream))
{
zipStream.PutNextEntry(new ZipEntry("data"));
formatter.Serialize(zipStream, data);
zipStream.CloseEntry();
zipStream.Close();
}
byte[] result = memStream.ToArray();
memStream.Close();
return result;
}
private object UnZipZeroLength(byte[] zipped)
{
if (zipped == null)
{
return null;
}
object result = null;
var formatter = new BinaryFormatter();
var memStream = new MemoryStream(zipped);
using (ZipInputStream zipStream = new ZipInputStream(memStream))
{
ZipEntry zipEntry = zipStream.GetNextEntry();
if (zipEntry != null)
{
result = formatter.Deserialize(zipStream);
}
zipStream.Close();
}
memStream.Close();
return result;
}
[Test]
[Category("Zip")]
[TestCase("Hello")]
[TestCase("a/b/c/d/e/f/g/h/SomethingLikeAnArchiveName.txt")]
public void LegacyNameConversion(string name)
{
var encoding = StringCodec.Default.ZipEncoding(false);
byte[] intermediate = encoding.GetBytes(name);
string final = encoding.GetString(intermediate);
Assert.AreEqual(name, final, "Expected identical result");
}
[Test]
[Category("Zip")]
public void UnicodeNameConversion()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var codec = StringCodec.FromCodePage(850);
string sample = "Hello world";
byte[] rawData = Encoding.ASCII.GetBytes(sample);
var converted = codec.LegacyEncoding.GetString(rawData);
Assert.AreEqual(sample, converted);
converted = codec.ZipInputEncoding(GeneralBitFlags.UnicodeText).GetString(rawData);
Assert.AreEqual(sample, converted);
// This time use some greek characters
sample = "\u03A5\u03d5\u03a3";
rawData = Encoding.UTF8.GetBytes(sample);
converted = codec.ZipInputEncoding(GeneralBitFlags.UnicodeText).GetString(rawData);
Assert.AreEqual(sample, converted);
}
/// <summary>
/// Regression test for problem where the password check would fail for an archive whose
/// date was updated from the extra data.
/// This applies to archives where the crc wasnt know at the time of encryption.
/// The date of the entry is used in its place.
/// </summary>
[Test]
[Category("Zip")]
[Ignore("at commit 60831547c868cc56d43f24473f7d5f2cc51fb754 this unit test passed but the behavior of ZipEntry.DateTime has changed completely ever since. Not sure if this unit test is still needed.")]
public void PasswordCheckingWithDateInExtraData()
{
var ms = new MemoryStream();
var checkTime = new DateTimeOffset(2010, 10, 16, 0, 3, 28, new TimeSpan(1, 0, 0));
using (ZipOutputStream zos = new ZipOutputStream(ms))
{
zos.IsStreamOwner = false;
zos.Password = "secret";
var ze = new ZipEntry("uno");
ze.DateTime = new DateTime(1998, 6, 5, 4, 3, 2);
var zed = new ZipExtraData();
zed.StartNewEntry();
zed.AddData(1);
TimeSpan delta = checkTime.UtcDateTime - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
var seconds = (int)delta.TotalSeconds;
zed.AddLeInt(seconds);
zed.AddNewEntry(0x5455);
ze.ExtraData = zed.GetEntryData();
zos.PutNextEntry(ze);
zos.WriteByte(54);
}
ms.Position = 0;
using (ZipInputStream zis = new ZipInputStream(ms))
{
zis.Password = "secret";
ZipEntry uno = zis.GetNextEntry();
var theByte = (byte)zis.ReadByte();
Assert.AreEqual(54, theByte);
Assert.AreEqual(-1, zis.ReadByte()); // eof
Assert.AreEqual(checkTime.DateTime, uno.DateTime);
}
}
[Test]
[Category("Zip")]
[Category("Encryption")]
public void ReadingEncryptedZipWithDirectories()
{
var ms = new MemoryStream();
using (ZipOutputStream outStream = new ZipOutputStream(ms))
{
outStream.IsStreamOwner = false;
outStream.Password = "testPassword123";
outStream.SetLevel(5);
var entry = new ZipEntry("Folder/");
outStream.PutNextEntry(entry);
entry = new ZipEntry("Folder/File.txt");
outStream.PutNextEntry(entry);
byte[] fileData = Encoding.UTF8.GetBytes("This is some test data");
outStream.Write(fileData, 0, fileData.Length);
}
ms.Seek(0, SeekOrigin.Begin);
using (ZipFile zipFile = new ZipFile(ms))
{
zipFile.BeginUpdate();
zipFile.IsStreamOwner = false;
zipFile.Password = "testPassword123";
zipFile.AddDirectory("Folder2/");
zipFile.Add(new MemoryDataSource(Encoding.UTF8.GetBytes("Test content")), "Folder2/File2.txt");
zipFile.CommitUpdate();
}
ms.Seek(0, SeekOrigin.Begin);
using (var inStream = new ZipInputStream(ms))
{
inStream.IsStreamOwner = false;
inStream.Password = "testPassword123";
ZipEntry fileEntry = inStream.GetNextEntry();
Assert.AreEqual("Folder/", fileEntry.Name);
fileEntry = inStream.GetNextEntry();
Assert.AreEqual("Folder/File.txt", fileEntry.Name);
fileEntry = inStream.GetNextEntry();
Assert.AreEqual("Folder2/", fileEntry.Name);
fileEntry = inStream.GetNextEntry();
Assert.AreEqual("Folder2/File2.txt", fileEntry.Name);
}
}
}
}