This repository has been archived by the owner on May 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathZipEntry.Extract.cs
1424 lines (1276 loc) · 58 KB
/
ZipEntry.Extract.cs
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ZipEntry.Extract.cs
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 Dino Chiesa
// All rights reserved.
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
//
// last saved (in emacs):
// Time-stamp: <2011-August-06 18:08:21>
//
// ------------------------------------------------------------------
//
// This module defines logic for Extract methods on the ZipEntry class.
//
// ------------------------------------------------------------------
using System;
using System.IO;
namespace Ionic.Zip
{
public partial class ZipEntry
{
/// <summary>
/// Extract the entry to the filesystem, starting at the current
/// working directory.
/// </summary>
///
/// <overloads>
/// This method has a bunch of overloads! One of them is sure to
/// be the right one for you... If you don't like these, check
/// out the <c>ExtractWithPassword()</c> methods.
/// </overloads>
///
/// <seealso cref="Ionic.Zip.ZipEntry.ExtractExistingFile"/>
/// <seealso cref="ZipEntry.Extract(ExtractExistingFileAction)"/>
///
/// <remarks>
///
/// <para>
/// This method extracts an entry from a zip file into the current
/// working directory. The path of the entry as extracted is the full
/// path as specified in the zip archive, relative to the current
/// working directory. After the file is extracted successfully, the
/// file attributes and timestamps are set.
/// </para>
///
/// <para>
/// The action taken when extraction an entry would overwrite an
/// existing file is determined by the <see cref="ExtractExistingFile"
/// /> property.
/// </para>
///
/// <para>
/// Within the call to <c>Extract()</c>, the content for the entry is
/// written into a filesystem file, and then the last modified time of the
/// file is set according to the <see cref="LastModified"/> property on
/// the entry. See the remarks the <see cref="LastModified"/> property for
/// some details about the last modified time.
/// </para>
///
/// </remarks>
public void Extract()
{
InternalExtractToBaseDir(".", null, _container, _Source, FileName);
}
/// <summary>
/// Extract the entry to a file in the filesystem, using the specified
/// behavior when extraction would overwrite an existing file.
/// </summary>
///
/// <remarks>
/// <para>
/// See the remarks on the <see cref="LastModified"/> property, for some
/// details about how the last modified time of the file is set after
/// extraction.
/// </para>
/// </remarks>
///
/// <param name="extractExistingFile">
/// The action to take if extraction would overwrite an existing file.
/// </param>
public void Extract(ExtractExistingFileAction extractExistingFile)
{
ExtractExistingFile = extractExistingFile;
InternalExtractToBaseDir(".", null, _container, _Source, FileName);
}
/// <summary>
/// Extracts the entry to the specified stream.
/// </summary>
///
/// <remarks>
/// <para>
/// The caller can specify any write-able stream, for example a <see
/// cref="System.IO.FileStream"/>, a <see
/// cref="System.IO.MemoryStream"/>, or ASP.NET's
/// <c>Response.OutputStream</c>. The content will be decrypted and
/// decompressed as necessary. If the entry is encrypted and no password
/// is provided, this method will throw.
/// </para>
/// <para>
/// The position on the stream is not reset by this method before it extracts.
/// You may want to call stream.Seek() before calling ZipEntry.Extract().
/// </para>
/// </remarks>
///
/// <param name="stream">
/// the stream to which the entry should be extracted.
/// </param>
///
public void Extract(Stream stream)
{
InternalExtractToStream(stream, null, _container, _Source, FileName);
}
/// <summary>
/// Extract the entry to the filesystem, starting at the specified base
/// directory.
/// </summary>
///
/// <param name="baseDirectory">the pathname of the base directory</param>
///
/// <seealso cref="Ionic.Zip.ZipEntry.ExtractExistingFile"/>
/// <seealso cref="Ionic.Zip.ZipEntry.Extract(string, ExtractExistingFileAction)"/>
///
/// <example>
/// This example extracts only the entries in a zip file that are .txt files,
/// into a directory called "textfiles".
/// <code lang="C#">
/// using (ZipFile zip = ZipFile.Read("PackedDocuments.zip"))
/// {
/// foreach (string s1 in zip.EntryFilenames)
/// {
/// if (s1.EndsWith(".txt"))
/// {
/// zip[s1].Extract("textfiles");
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip")
/// Dim s1 As String
/// For Each s1 In zip.EntryFilenames
/// If s1.EndsWith(".txt") Then
/// zip(s1).Extract("textfiles")
/// End If
/// Next
/// End Using
/// </code>
/// </example>
///
/// <remarks>
///
/// <para>
/// Using this method, existing entries in the filesystem will not be
/// overwritten. If you would like to force the overwrite of existing
/// files, see the <see cref="ExtractExistingFile"/> property, or call
/// <see cref="Extract(string, ExtractExistingFileAction)"/>.
/// </para>
///
/// <para>
/// See the remarks on the <see cref="LastModified"/> property, for some
/// details about how the last modified time of the created file is set.
/// </para>
/// </remarks>
public void Extract(string baseDirectory)
{
InternalExtractToBaseDir(baseDirectory, null, _container, _Source, FileName);
}
/// <summary>
/// Extract the entry to the filesystem, starting at the specified base
/// directory, and using the specified behavior when extraction would
/// overwrite an existing file.
/// </summary>
///
/// <remarks>
/// <para>
/// See the remarks on the <see cref="LastModified"/> property, for some
/// details about how the last modified time of the created file is set.
/// </para>
/// </remarks>
///
/// <example>
/// <code lang="C#">
/// String sZipPath = "Airborne.zip";
/// String sFilePath = "Readme.txt";
/// String sRootFolder = "Digado";
/// using (ZipFile zip = ZipFile.Read(sZipPath))
/// {
/// if (zip.EntryFileNames.Contains(sFilePath))
/// {
/// // use the string indexer on the zip file
/// zip[sFileName].Extract(sRootFolder,
/// ExtractExistingFileAction.OverwriteSilently);
/// }
/// }
/// </code>
///
/// <code lang="VB">
/// Dim sZipPath as String = "Airborne.zip"
/// Dim sFilePath As String = "Readme.txt"
/// Dim sRootFolder As String = "Digado"
/// Using zip As ZipFile = ZipFile.Read(sZipPath)
/// If zip.EntryFileNames.Contains(sFilePath)
/// ' use the string indexer on the zip file
/// zip(sFilePath).Extract(sRootFolder, _
/// ExtractExistingFileAction.OverwriteSilently)
/// End If
/// End Using
/// </code>
/// </example>
///
/// <param name="baseDirectory">the pathname of the base directory</param>
/// <param name="extractExistingFile">
/// The action to take if extraction would overwrite an existing file.
/// </param>
public void Extract(string baseDirectory, ExtractExistingFileAction extractExistingFile)
{
ExtractExistingFile = extractExistingFile;
InternalExtractToBaseDir(baseDirectory, null, _container, _Source, FileName);
}
/// <summary>
/// Extract the entry to the filesystem, using the current working directory
/// and the specified password.
/// </summary>
///
/// <overloads>
/// This method has a bunch of overloads! One of them is sure to be
/// the right one for you...
/// </overloads>
///
/// <seealso cref="Ionic.Zip.ZipEntry.ExtractExistingFile"/>
/// <seealso cref="Ionic.Zip.ZipEntry.ExtractWithPassword(ExtractExistingFileAction, string)"/>
///
/// <remarks>
///
/// <para>
/// Existing entries in the filesystem will not be overwritten. If you
/// would like to force the overwrite of existing files, see the <see
/// cref="Ionic.Zip.ZipEntry.ExtractExistingFile"/>property, or call
/// <see
/// cref="ExtractWithPassword(ExtractExistingFileAction,string)"/>.
/// </para>
///
/// <para>
/// See the remarks on the <see cref="LastModified"/> property for some
/// details about how the "last modified" time of the created file is
/// set.
/// </para>
/// </remarks>
///
/// <example>
/// In this example, entries that use encryption are extracted using a
/// particular password.
/// <code>
/// using (var zip = ZipFile.Read(FilePath))
/// {
/// foreach (ZipEntry e in zip)
/// {
/// if (e.UsesEncryption)
/// e.ExtractWithPassword("Secret!");
/// else
/// e.Extract();
/// }
/// }
/// </code>
/// <code lang="VB">
/// Using zip As ZipFile = ZipFile.Read(FilePath)
/// Dim e As ZipEntry
/// For Each e In zip
/// If (e.UsesEncryption)
/// e.ExtractWithPassword("Secret!")
/// Else
/// e.Extract
/// End If
/// Next
/// End Using
/// </code>
/// </example>
/// <param name="password">The Password to use for decrypting the entry.</param>
public void ExtractWithPassword(string password)
{
InternalExtractToBaseDir(".", password, _container, _Source, FileName);
}
/// <summary>
/// Extract the entry to the filesystem, starting at the specified base
/// directory, and using the specified password.
/// </summary>
///
/// <seealso cref="Ionic.Zip.ZipEntry.ExtractExistingFile"/>
/// <seealso cref="Ionic.Zip.ZipEntry.ExtractWithPassword(string, ExtractExistingFileAction, string)"/>
///
/// <remarks>
/// <para>
/// Existing entries in the filesystem will not be overwritten. If you
/// would like to force the overwrite of existing files, see the <see
/// cref="Ionic.Zip.ZipEntry.ExtractExistingFile"/>property, or call
/// <see
/// cref="ExtractWithPassword(ExtractExistingFileAction,string)"/>.
/// </para>
///
/// <para>
/// See the remarks on the <see cref="LastModified"/> property, for some
/// details about how the last modified time of the created file is set.
/// </para>
/// </remarks>
///
/// <param name="baseDirectory">The pathname of the base directory.</param>
/// <param name="password">The Password to use for decrypting the entry.</param>
public void ExtractWithPassword(string baseDirectory, string password)
{
InternalExtractToBaseDir(baseDirectory, password, _container, _Source, FileName);
}
/// <summary>
/// Extract the entry to a file in the filesystem, relative to the
/// current directory, using the specified behavior when extraction
/// would overwrite an existing file.
/// </summary>
///
/// <remarks>
/// <para>
/// See the remarks on the <see cref="LastModified"/> property, for some
/// details about how the last modified time of the created file is set.
/// </para>
/// </remarks>
///
/// <param name="password">The Password to use for decrypting the entry.</param>
///
/// <param name="extractExistingFile">
/// The action to take if extraction would overwrite an existing file.
/// </param>
public void ExtractWithPassword(ExtractExistingFileAction extractExistingFile, string password)
{
ExtractExistingFile = extractExistingFile;
InternalExtractToBaseDir(".", password, _container, _Source, FileName);
}
/// <summary>
/// Extract the entry to the filesystem, starting at the specified base
/// directory, and using the specified behavior when extraction would
/// overwrite an existing file.
/// </summary>
///
/// <remarks>
/// See the remarks on the <see cref="LastModified"/> property, for some
/// details about how the last modified time of the created file is set.
/// </remarks>
///
/// <param name="baseDirectory">the pathname of the base directory</param>
///
/// <param name="extractExistingFile">The action to take if extraction would
/// overwrite an existing file.</param>
///
/// <param name="password">The Password to use for decrypting the entry.</param>
public void ExtractWithPassword(string baseDirectory, ExtractExistingFileAction extractExistingFile, string password)
{
ExtractExistingFile = extractExistingFile;
InternalExtractToBaseDir(baseDirectory, password, _container, _Source, FileName);
}
/// <summary>
/// Extracts the entry to the specified stream, using the specified
/// Password. For example, the caller could extract to Console.Out, or
/// to a MemoryStream.
/// </summary>
///
/// <remarks>
/// <para>
/// The caller can specify any write-able stream, for example a <see
/// cref="System.IO.FileStream"/>, a <see
/// cref="System.IO.MemoryStream"/>, or ASP.NET's
/// <c>Response.OutputStream</c>. The content will be decrypted and
/// decompressed as necessary. If the entry is encrypted and no password
/// is provided, this method will throw.
/// </para>
/// <para>
/// The position on the stream is not reset by this method before it extracts.
/// You may want to call stream.Seek() before calling ZipEntry.Extract().
/// </para>
/// </remarks>
///
///
/// <param name="stream">
/// the stream to which the entry should be extracted.
/// </param>
/// <param name="password">
/// The password to use for decrypting the entry.
/// </param>
public void ExtractWithPassword(Stream stream, string password)
{
InternalExtractToStream(stream, password, _container, _Source, FileName);
}
/// <summary>
/// Opens a readable stream corresponding to the zip entry in the
/// archive. The stream decompresses and decrypts as necessary, as it
/// is read.
/// </summary>
///
/// <remarks>
///
/// <para>
/// DotNetZip offers a variety of ways to extract entries from a zip
/// file. This method allows an application to extract an entry by
/// reading a <see cref="System.IO.Stream"/>.
/// </para>
///
/// <para>
/// The return value is of type <see
/// cref="Ionic.Crc.CrcCalculatorStream"/>. Use it as you would any
/// stream for reading. When an application calls <see
/// cref="Stream.Read(byte[], int, int)"/> on that stream, it will
/// receive data from the zip entry that is decrypted and decompressed
/// as necessary.
/// </para>
///
/// <para>
/// <c>CrcCalculatorStream</c> adds one additional feature: it keeps a
/// CRC32 checksum on the bytes of the stream as it is read. The CRC
/// value is available in the <see
/// cref="Ionic.Crc.CrcCalculatorStream.Crc"/> property on the
/// <c>CrcCalculatorStream</c>. When the read is complete, your
/// application
/// <em>should</em> check this CRC against the <see cref="ZipEntry.Crc"/>
/// property on the <c>ZipEntry</c> to validate the content of the
/// ZipEntry. You don't have to validate the entry using the CRC, but
/// you should, to verify integrity. Check the example for how to do
/// this.
/// </para>
///
/// <para>
/// If the entry is protected with a password, then you need to provide
/// a password prior to calling <see cref="OpenReader()"/>, either by
/// setting the <see cref="Password"/> property on the entry, or the
/// <see cref="ZipFile.Password"/> property on the <c>ZipFile</c>
/// itself. Or, you can use <see cref="OpenReader(String)" />, the
/// overload of OpenReader that accepts a password parameter.
/// </para>
///
/// <para>
/// If you want to extract entry data into a write-able stream that is
/// already opened, like a <see cref="System.IO.FileStream"/>, do not
/// use this method. Instead, use <see cref="Extract(Stream)"/>.
/// </para>
///
/// <para>
/// Your application may use only one stream created by OpenReader() at
/// a time, and you should not call other Extract methods before
/// completing your reads on a stream obtained from OpenReader(). This
/// is because there is really only one source stream for the compressed
/// content. A call to OpenReader() seeks in the source stream, to the
/// beginning of the compressed content. A subsequent call to
/// OpenReader() on a different entry will seek to a different position
/// in the source stream, as will a call to Extract() or one of its
/// overloads. This will corrupt the state for the decompressing stream
/// from the original call to OpenReader().
/// </para>
///
/// <para>
/// The <c>OpenReader()</c> method works only when the ZipEntry is
/// obtained from an instance of <c>ZipFile</c>. This method will throw
/// an exception if the ZipEntry is obtained from a <see
/// cref="ZipInputStream"/>.
/// </para>
/// </remarks>
///
/// <example>
/// This example shows how to open a zip archive, then read in a named
/// entry via a stream. After the read loop is complete, the code
/// compares the calculated during the read loop with the expected CRC
/// on the <c>ZipEntry</c>, to verify the extraction.
/// <code>
/// using (ZipFile zip = new ZipFile(ZipFileToRead))
/// {
/// ZipEntry e1= zip["Elevation.mp3"];
/// using (Ionic.Zlib.CrcCalculatorStream s = e1.OpenReader())
/// {
/// byte[] buffer = new byte[4096];
/// int n, totalBytesRead= 0;
/// do {
/// n = s.Read(buffer,0, buffer.Length);
/// totalBytesRead+=n;
/// } while (n>0);
/// if (s.Crc32 != e1.Crc32)
/// throw new Exception(string.Format("The Zip Entry failed the CRC Check. (0x{0:X8}!=0x{1:X8})", s.Crc32, e1.Crc32));
/// if (totalBytesRead != e1.UncompressedSize)
/// throw new Exception(string.Format("We read an unexpected number of bytes. ({0}!={1})", totalBytesRead, e1.UncompressedSize));
/// }
/// }
/// </code>
/// <code lang="VB">
/// Using zip As New ZipFile(ZipFileToRead)
/// Dim e1 As ZipEntry = zip.Item("Elevation.mp3")
/// Using s As Ionic.Zlib.CrcCalculatorStream = e1.OpenReader
/// Dim n As Integer
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim totalBytesRead As Integer = 0
/// Do
/// n = s.Read(buffer, 0, buffer.Length)
/// totalBytesRead = (totalBytesRead + n)
/// Loop While (n > 0)
/// If (s.Crc32 <> e1.Crc32) Then
/// Throw New Exception(String.Format("The Zip Entry failed the CRC Check. (0x{0:X8}!=0x{1:X8})", s.Crc32, e1.Crc32))
/// End If
/// If (totalBytesRead <> e1.UncompressedSize) Then
/// Throw New Exception(String.Format("We read an unexpected number of bytes. ({0}!={1})", totalBytesRead, e1.UncompressedSize))
/// End If
/// End Using
/// End Using
/// </code>
/// </example>
/// <seealso cref="Ionic.Zip.ZipEntry.Extract(System.IO.Stream)"/>
/// <returns>The Stream for reading.</returns>
public Crc.CrcCalculatorStream OpenReader()
{
// workitem 10923
if (_container.ZipFile == null)
throw new InvalidOperationException("Use OpenReader() only with ZipFile.");
// use the entry password if it is non-null,
// else use the zipfile password, which is possibly null
return InternalOpenReader(_Password ?? _container.Password);
}
/// <summary>
/// Opens a readable stream for an encrypted zip entry in the archive.
/// The stream decompresses and decrypts as necessary, as it is read.
/// </summary>
///
/// <remarks>
/// <para>
/// See the documentation on the <see cref="OpenReader()"/> method for
/// full details. This overload allows the application to specify a
/// password for the <c>ZipEntry</c> to be read.
/// </para>
/// </remarks>
///
/// <param name="password">The password to use for decrypting the entry.</param>
/// <returns>The Stream for reading.</returns>
public Ionic.Crc.CrcCalculatorStream OpenReader(string password)
{
// workitem 10923
if (_container.ZipFile == null)
throw new InvalidOperationException("Use OpenReader() only with ZipFile.");
return InternalOpenReader(password);
}
internal Crc.CrcCalculatorStream InternalOpenReader(string password)
{
ValidateCompression(_CompressionMethod_FromZipFile, FileName, GetUnsupportedCompressionMethod(_CompressionMethod));
ValidateEncryption(Encryption, FileName, _UnsupportedAlgorithmId);
SetupCryptoForExtract(password);
// workitem 7958
if (this._Source != ZipEntrySource.ZipFile)
throw new BadStateException("You must call ZipFile.Save before calling OpenReader");
// LeftToRead is a count of bytes remaining to be read (out)
// from the stream AFTER decompression and decryption.
// It is the uncompressed size, unless ... there is no compression in which
// case ...? :< I'm not sure why it's not always UncompressedSize
var leftToRead = (_CompressionMethod_FromZipFile == (short)CompressionMethod.None)
? _CompressedFileDataSize
: UncompressedSize;
this.ArchiveStream.Seek(this.FileDataPosition, SeekOrigin.Begin);
_inputDecryptorStream = GetExtractDecryptor(ArchiveStream);
var input3 = GetExtractDecompressor(_inputDecryptorStream);
return new Crc.CrcCalculatorStream(input3, leftToRead);
}
void OnExtractProgress(Int64 bytesWritten, Int64 totalBytesToWrite)
{
if (_container.ZipFile != null)
_ioOperationCanceled = _container.ZipFile.OnExtractBlock(this, bytesWritten, totalBytesToWrite);
}
static void OnBeforeExtract(ZipEntry zipEntryInstance, string path, ZipFile zipFile)
{
// When in the context of a ZipFile.ExtractAll, the events are generated from
// the ZipFile method, not from within the ZipEntry instance. (why?)
// Therefore we suppress the events originating from the ZipEntry method.
if (zipFile == null) return;
if (zipFile._inExtractAll) return;
// returned boolean is always ignored for all callers of OnBeforeExtract
zipFile.OnSingleEntryExtract(zipEntryInstance, path, true);
}
private void OnAfterExtract(string path)
{
// When in the context of a ZipFile.ExtractAll, the events are generated from
// the ZipFile method, not from within the ZipEntry instance. (why?)
// Therefore we suppress the events originating from the ZipEntry method.
if (_container.ZipFile == null) return;
if (_container.ZipFile._inExtractAll) return;
_container.ZipFile.OnSingleEntryExtract(this, path, false);
}
private void OnExtractExisting(string path)
{
if (_container.ZipFile != null)
_ioOperationCanceled = _container.ZipFile.OnExtractExisting(this, path);
}
private static void ReallyDelete(string fileName)
{
// workitem 7881
// reset ReadOnly bit if necessary
if ((File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
File.SetAttributes(fileName, FileAttributes.Normal);
File.Delete(fileName);
}
void WriteStatus(string format, params Object[] args)
{
if (_container.ZipFile != null && _container.ZipFile.Verbose)
_container.ZipFile.StatusMessageTextWriter.WriteLine(format, args);
}
/// <summary>
/// Pass in either basedir or s, but not both.
/// In other words, you can extract to a stream or to a directory (filesystem), but not both!
/// The Password param is required for encrypted entries.
/// </summary>
void InternalExtractToBaseDir(string baseDir, string password, ZipContainer zipContainer, ZipEntrySource zipEntrySource, string fileName)
{
if (baseDir == null)
throw new ArgumentNullException("baseDir");
// workitem 7958
if (zipContainer == null)
throw new BadStateException("This entry is an orphan");
// workitem 10355
if (zipContainer.ZipFile == null)
throw new InvalidOperationException("Use Extract() only with ZipFile.");
zipContainer.ZipFile.Reset(false);
if (zipEntrySource != ZipEntrySource.ZipFile)
throw new BadStateException("You must call ZipFile.Save before calling any Extract method");
OnBeforeExtract(this, baseDir, zipContainer.ZipFile);
_ioOperationCanceled = false;
var fileExistsBeforeExtraction = false;
var checkLaterForResetDirTimes = false;
string targetFileName = null;
try
{
ValidateCompression(_CompressionMethod_FromZipFile, fileName, GetUnsupportedCompressionMethod(_CompressionMethod));
ValidateEncryption(Encryption, fileName, _UnsupportedAlgorithmId);
if (IsDoneWithOutputToBaseDir(baseDir, out targetFileName))
{
WriteStatus("extract dir {0}...", targetFileName);
// if true, then the entry was a directory and has been created.
// We need to fire the Extract Event.
OnAfterExtract(baseDir);
return;
}
// workitem 10639
// do we want to extract to a regular filesystem file?
// Check for extracting to a previously existing file. The user
// can specify bejavior for that case: overwrite, don't
// overwrite, and throw. Also, if the file exists prior to
// extraction, it affects exception handling: whether to delete
// the target of extraction or not. This check needs to be done
// before the password check is done, because password check may
// throw a BadPasswordException, which triggers the catch,
// wherein the existing file may be deleted if not flagged as
// pre-existing.
if (File.Exists(targetFileName))
{
fileExistsBeforeExtraction = true;
int rc = CheckExtractExistingFile(baseDir, targetFileName);
if (rc == 2) goto ExitTry; // cancel
if (rc == 1) return; // do not overwrite
}
// If no password explicitly specified, use the password on the entry itself,
// or on the zipfile itself.
if (_Encryption_FromZipFile != EncryptionAlgorithm.None)
EnsurePassword(password);
// set up the output stream
var tmpName = SharedUtilities.InternalGetTempFileName();
var tmpPath = Path.Combine(Path.GetDirectoryName(targetFileName), tmpName);
WriteStatus("extract file {0}...", targetFileName);
using (var output = OpenFileStream(tmpPath, ref checkLaterForResetDirTimes))
{
if (ExtractToStream(ArchiveStream, output, Encryption, _Crc32))
goto ExitTry;
output.Close();
}
MoveFileInPlace(fileExistsBeforeExtraction, targetFileName, tmpPath, checkLaterForResetDirTimes);
OnAfterExtract(baseDir);
ExitTry: ;
}
catch (Exception)
{
_ioOperationCanceled = true;
throw;
}
finally
{
if (_ioOperationCanceled && targetFileName != null)
{
// An exception has occurred. If the file exists, check
// to see if it existed before we tried extracting. If
// it did not, attempt to remove the target file. There
// is a small possibility that the existing file has
// been extracted successfully, overwriting a previously
// existing file, and an exception was thrown after that
// but before final completion (setting times, etc). In
// that case the file will remain, even though some
// error occurred. Nothing to be done about it.
if (File.Exists(targetFileName) && !fileExistsBeforeExtraction)
File.Delete(targetFileName);
}
}
}
/// <summary>
/// Extract to a stream
/// In other words, you can extract to a stream or to a directory (filesystem), but not both!
/// The Password param is required for encrypted entries.
/// </summary>
void InternalExtractToStream(Stream outStream, string password, ZipContainer zipContainer, ZipEntrySource zipEntrySource, string fileName)
{
// workitem 7958
if (zipContainer == null)
throw new BadStateException("This entry is an orphan");
// workitem 10355
if (zipContainer.ZipFile == null)
throw new InvalidOperationException("Use Extract() only with ZipFile.");
zipContainer.ZipFile.Reset(false);
if (zipEntrySource != ZipEntrySource.ZipFile)
throw new BadStateException("You must call ZipFile.Save before calling any Extract method");
OnBeforeExtract(this, null, zipContainer.ZipFile);
_ioOperationCanceled = false;
try
{
ValidateCompression(_CompressionMethod_FromZipFile, fileName, GetUnsupportedCompressionMethod(_CompressionMethod));
ValidateEncryption(Encryption, fileName, _UnsupportedAlgorithmId);
if (IsDoneWithOutputToStream())
{
WriteStatus("extract dir {0}...", null);
// if true, then the entry was a directory and has been created.
// We need to fire the Extract Event.
OnAfterExtract(null);
return;
}
// If no password explicitly specified, use the password on the entry itself,
// or on the zipfile itself.
if (_Encryption_FromZipFile != EncryptionAlgorithm.None)
EnsurePassword(password);
WriteStatus("extract entry {0} to stream...", fileName);
var archiveStream = ArchiveStream;
if (ExtractToStream(archiveStream, outStream, Encryption, _Crc32))
goto ExitTry;
OnAfterExtract(null);
ExitTry: ;
}
catch (Exception)
{
_ioOperationCanceled = true;
throw;
}
}
bool ExtractToStream(Stream archiveStream, Stream output, EncryptionAlgorithm encryptionAlgorithm, int expectedCrc32)
{
if (_ioOperationCanceled)
return true;
try
{
var calculatedCrc32 = ExtractAndCrc(archiveStream, output,
_CompressionMethod_FromZipFile, _CompressedFileDataSize,
UncompressedSize);
if (_ioOperationCanceled)
return true;
VerifyCrcAfterExtract(calculatedCrc32, encryptionAlgorithm, expectedCrc32, archiveStream, UncompressedSize);
return false;
}
finally
{
var zss = archiveStream as ZipSegmentedStream;
if (zss != null)
{
// need to dispose it
zss.Dispose();
_archiveStream = null;
}
}
}
void MoveFileInPlace(
bool fileExistsBeforeExtraction,
string targetFileName,
string tmpPath, bool checkLaterForResetDirTimes)
{
// workitem 10639
// move file to permanent home
string zombie = null;
if (fileExistsBeforeExtraction)
{
// An AV program may hold the target file open, which means
// File.Delete() will succeed, though the actual deletion
// remains pending. This will prevent a subsequent
// File.Move() from succeeding. To avoid this, when the file
// already exists, we need to replace it in 3 steps:
//
// 1. rename the existing file to a zombie name;
// 2. rename the extracted file from the temp name to
// the target file name;
// 3. delete the zombie.
//
zombie = targetFileName + Path.GetRandomFileName() + ".PendingOverwrite";
File.Move(targetFileName, zombie);
}
File.Move(tmpPath, targetFileName);
_SetTimes(targetFileName, true);
if (zombie != null && File.Exists(zombie))
ReallyDelete(zombie);
// workitem 8264
if (checkLaterForResetDirTimes)
{
// This is sort of a hack. What I do here is set the time on
// the parent directory, every time a file is extracted into
// it. If there is a directory with 1000 files, then I set
// the time on the dir, 1000 times. This allows the directory
// to have times that reflect the actual time on the entry in
// the zip archive.
if (FileName.Contains("/"))
{
var dirname = Path.GetDirectoryName(FileName);
if (_container.ZipFile[dirname] == null)
_SetTimes(Path.GetDirectoryName(targetFileName), false);
}
}
// workitem 7071
//
// We can only apply attributes if they are relevant to the NTFS
// OS. Must do this LAST because it may involve a ReadOnly bit,
// which would prevent us from setting the time, etc.
//
// workitem 7926 - version made by OS can be zero (FAT) or 10
// (NTFS)
if ((_VersionMadeBy & 0xFF00) == 0x0a00 || (_VersionMadeBy & 0xFF00) == 0x0000)
File.SetAttributes(targetFileName, (FileAttributes) _ExternalFileAttrs);
}
void EnsurePassword(string password)
{
var p = password ?? _Password ?? _container.Password;
if (p == null) throw new BadPasswordException();
SetupCryptoForExtract(p);
}
Stream OpenFileStream(string tmpPath, ref bool checkLaterForResetDirTimes)
{
var dirName = Path.GetDirectoryName(tmpPath);
// ensure the target path exists
if (!Directory.Exists(dirName))
{
// we create the directory here, but we do not set the
// create/modified/accessed times on it because it is being
// created implicitly, not explcitly. There's no entry in the
// zip archive for the directory.
Directory.CreateDirectory(dirName);
}
else
{
// workitem 8264
if (_container.ZipFile != null)
checkLaterForResetDirTimes = _container.ZipFile._inExtractAll;
}
// File.Create(CreateNew) will overwrite any existing file.
return new FileStream(tmpPath, FileMode.CreateNew);
}
#if NOT
internal void CalcWinZipAesMac(Stream input)
{
if (Encryption == EncryptionAlgorithm.WinZipAes128 ||
Encryption == EncryptionAlgorithm.WinZipAes256)
{
if (input is WinZipAesCipherStream)
wzs = input as WinZipAesCipherStream;
else if (input is Ionic.Zlib.CrcCalculatorStream)
{
xxx;
}
}
}
#endif
internal void VerifyCrcAfterExtract(Int32 calculatedCrc32, EncryptionAlgorithm encryptionAlgorithm, int expectedCrc32, Stream archiveStream, long uncompressedSize)
{
#if AESCRYPTO
// After extracting, Validate the CRC32
if (calculatedCrc32 != expectedCrc32)
{
// CRC is not meaningful with WinZipAES and AES method 2 (AE-2)
if ((encryptionAlgorithm != EncryptionAlgorithm.WinZipAes128 &&
encryptionAlgorithm != EncryptionAlgorithm.WinZipAes256)
|| _WinZipAesMethod != 0x02)
throw new BadCrcException("CRC error: the file being extracted appears to be corrupted. " +
String.Format("Expected 0x{0:X8}, Actual 0x{1:X8}", expectedCrc32, calculatedCrc32));
}
// ignore MAC if the size of the file is zero
if (uncompressedSize == 0)
return;
// calculate the MAC
if (encryptionAlgorithm == EncryptionAlgorithm.WinZipAes128 ||
encryptionAlgorithm == EncryptionAlgorithm.WinZipAes256)
{
var wzs = _inputDecryptorStream as WinZipAesCipherStream;
// sometimes there are extra bytes in the WinZipAES stream that were not required to generate
// the decryption output. Read and ignore these bytes, so that the CRC can be calculated:
byte[] throwAwayBuffer = new byte[256];
wzs.Read(throwAwayBuffer, 0, 256);
_aesCrypto_forExtract.CalculatedMac = wzs.FinalAuthentication;
_aesCrypto_forExtract.ReadAndVerifyMac(archiveStream); // throws if MAC is bad
// side effect: advances file position.
}
#else
if (calculatedCrc32 != expectedCrc32)
throw new BadCrcException("CRC error: the file being extracted appears to be corrupted. " +
String.Format("Expected 0x{0:X8}, Actual 0x{1:X8}", expectedCrc32, calculatedCrc32));
#endif
}
int CheckExtractExistingFile(string baseDir, string targetFileName)
{
int loop = 0;
// returns: 0 == extract, 1 = don't, 2 = cancel
do