/
ZipArchiveEntry.cs
1317 lines (1142 loc) · 57.3 KB
/
ZipArchiveEntry.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.IO.Compression.ZipArchiveEntryConstants;
namespace System.IO.Compression
{
// The disposable fields that this class owns get disposed when the ZipArchive it belongs to gets disposed
public partial class ZipArchiveEntry
{
private ZipArchive _archive;
private readonly bool _originallyInArchive;
private readonly int _diskNumberStart;
private readonly ZipVersionMadeByPlatform _versionMadeByPlatform;
private ZipVersionNeededValues _versionMadeBySpecification;
internal ZipVersionNeededValues _versionToExtract;
private BitFlagValues _generalPurposeBitFlag;
private bool _isEncrypted;
private CompressionMethodValues _storedCompressionMethod;
private DateTimeOffset _lastModified;
private long _compressedSize;
private long _uncompressedSize;
private long _offsetOfLocalHeader;
private long? _storedOffsetOfCompressedData;
private uint _crc32;
// An array of buffers, each a maximum of MaxSingleBufferSize in size
private byte[][]? _compressedBytes;
private MemoryStream? _storedUncompressedData;
private bool _currentlyOpenForWrite;
private bool _everOpenedForWrite;
private Stream? _outstandingWriteStream;
private uint _externalFileAttr;
private string _storedEntryName;
private byte[] _storedEntryNameBytes;
// only apply to update mode
private List<ZipGenericExtraField>? _cdUnknownExtraFields;
private List<ZipGenericExtraField>? _lhUnknownExtraFields;
private byte[] _fileComment;
private readonly CompressionLevel? _compressionLevel;
// Initializes a ZipArchiveEntry instance for an existing archive entry.
internal ZipArchiveEntry(ZipArchive archive, ZipCentralDirectoryFileHeader cd)
{
_archive = archive;
_originallyInArchive = true;
_diskNumberStart = cd.DiskNumberStart;
_versionMadeByPlatform = (ZipVersionMadeByPlatform)cd.VersionMadeByCompatibility;
_versionMadeBySpecification = (ZipVersionNeededValues)cd.VersionMadeBySpecification;
_versionToExtract = (ZipVersionNeededValues)cd.VersionNeededToExtract;
_generalPurposeBitFlag = (BitFlagValues)cd.GeneralPurposeBitFlag;
_isEncrypted = (_generalPurposeBitFlag & BitFlagValues.IsEncrypted) != 0;
CompressionMethod = (CompressionMethodValues)cd.CompressionMethod;
_lastModified = new DateTimeOffset(ZipHelper.DosTimeToDateTime(cd.LastModified));
_compressedSize = cd.CompressedSize;
_uncompressedSize = cd.UncompressedSize;
_externalFileAttr = cd.ExternalFileAttributes;
_offsetOfLocalHeader = cd.RelativeOffsetOfLocalHeader;
// we don't know this yet: should be _offsetOfLocalHeader + 30 + _storedEntryNameBytes.Length + extrafieldlength
// but entryname/extra length could be different in LH
_storedOffsetOfCompressedData = null;
_crc32 = cd.Crc32;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
_storedEntryNameBytes = cd.Filename;
_storedEntryName = (_archive.EntryNameAndCommentEncoding ?? Encoding.UTF8).GetString(_storedEntryNameBytes);
DetectEntryNameVersion();
_lhUnknownExtraFields = null;
// the cd should have this as null if we aren't in Update mode
_cdUnknownExtraFields = cd.ExtraFields;
_fileComment = cd.FileComment;
_compressionLevel = null;
}
// Initializes a ZipArchiveEntry instance for a new archive entry with a specified compression level.
internal ZipArchiveEntry(ZipArchive archive, string entryName, CompressionLevel compressionLevel)
: this(archive, entryName)
{
_compressionLevel = compressionLevel;
if (_compressionLevel == CompressionLevel.NoCompression)
{
CompressionMethod = CompressionMethodValues.Stored;
}
}
// Initializes a ZipArchiveEntry instance for a new archive entry.
internal ZipArchiveEntry(ZipArchive archive, string entryName)
{
_archive = archive;
_originallyInArchive = false;
_diskNumberStart = 0;
_versionMadeByPlatform = CurrentZipPlatform;
_versionMadeBySpecification = ZipVersionNeededValues.Default;
_versionToExtract = ZipVersionNeededValues.Default; // this must happen before following two assignment
_generalPurposeBitFlag = 0;
CompressionMethod = CompressionMethodValues.Deflate;
_lastModified = DateTimeOffset.Now;
_compressedSize = 0; // we don't know these yet
_uncompressedSize = 0;
UnixFileMode defaultEntryPermissions = entryName.EndsWith(Path.DirectorySeparatorChar) || entryName.EndsWith(Path.AltDirectorySeparatorChar)
? DefaultDirectoryEntryPermissions
: DefaultFileEntryPermissions;
_externalFileAttr = (uint)(defaultEntryPermissions) << 16;
_offsetOfLocalHeader = 0;
_storedOffsetOfCompressedData = null;
_crc32 = 0;
_compressedBytes = null;
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
_outstandingWriteStream = null;
FullName = entryName;
_cdUnknownExtraFields = null;
_lhUnknownExtraFields = null;
_fileComment = Array.Empty<byte>();
_compressionLevel = null;
if (_storedEntryNameBytes.Length > ushort.MaxValue)
throw new ArgumentException(SR.EntryNamesTooLong);
// grab the stream if we're in create mode
if (_archive.Mode == ZipArchiveMode.Create)
{
_archive.AcquireArchiveStream(this);
}
}
/// <summary>
/// The ZipArchive that this entry belongs to. If this entry has been deleted, this will return null.
/// </summary>
public ZipArchive Archive => _archive;
[CLSCompliant(false)]
public uint Crc32 => _crc32;
/// <summary>
/// Gets a value that indicates whether the entry is encrypted.
/// </summary>
public bool IsEncrypted => _isEncrypted;
/// <summary>
/// The compressed size of the entry. If the archive that the entry belongs to is in Create mode, attempts to get this property will always throw an exception. If the archive that the entry belongs to is in update mode, this property will only be valid if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public long CompressedLength
{
get
{
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _compressedSize;
}
}
public int ExternalAttributes
{
get
{
return (int)_externalFileAttr;
}
set
{
ThrowIfInvalidArchive();
_externalFileAttr = (uint)value;
}
}
/// <summary>
/// Gets or sets the optional entry comment.
/// </summary>
/// <remarks>
///The comment encoding is determined by the <c>entryNameEncoding</c> parameter of the <see cref="ZipArchive(Stream,ZipArchiveMode,bool,Encoding?)"/> constructor.
/// If the comment byte length is larger than <see cref="ushort.MaxValue"/>, it will be truncated when disposing the archive.
/// </remarks>
[AllowNull]
public string Comment
{
get => (_archive.EntryNameAndCommentEncoding ?? Encoding.UTF8).GetString(_fileComment);
set
{
_fileComment = ZipHelper.GetEncodedTruncatedBytesFromString(value, _archive.EntryNameAndCommentEncoding, ushort.MaxValue, out bool isUTF8);
if (isUTF8)
{
_generalPurposeBitFlag |= BitFlagValues.UnicodeFileNameAndComment;
}
}
}
/// <summary>
/// The relative path of the entry as stored in the Zip archive. Note that Zip archives allow any string to be the path of the entry, including invalid and absolute paths.
/// </summary>
public string FullName
{
get
{
return _storedEntryName;
}
[MemberNotNull(nameof(_storedEntryNameBytes))]
[MemberNotNull(nameof(_storedEntryName))]
private set
{
ArgumentNullException.ThrowIfNull(value, nameof(FullName));
_storedEntryNameBytes = ZipHelper.GetEncodedTruncatedBytesFromString(
value, _archive.EntryNameAndCommentEncoding, 0 /* No truncation */, out bool isUTF8);
_storedEntryName = value;
if (isUTF8)
{
_generalPurposeBitFlag |= BitFlagValues.UnicodeFileNameAndComment;
}
else
{
_generalPurposeBitFlag &= ~BitFlagValues.UnicodeFileNameAndComment;
}
DetectEntryNameVersion();
}
}
/// <summary>
/// The last write time of the entry as stored in the Zip archive. When setting this property, the DateTime will be converted to the
/// Zip timestamp format, which supports a resolution of two seconds. If the data in the last write time field is not a valid Zip timestamp,
/// an indicator value of 1980 January 1 at midnight will be returned.
/// </summary>
/// <exception cref="NotSupportedException">An attempt to set this property was made, but the ZipArchive that this entry belongs to was
/// opened in read-only mode.</exception>
/// <exception cref="ArgumentOutOfRangeException">An attempt was made to set this property to a value that cannot be represented in the
/// Zip timestamp format. The earliest date/time that can be represented is 1980 January 1 0:00:00 (midnight), and the last date/time
/// that can be represented is 2107 December 31 23:59:58 (one second before midnight).</exception>
public DateTimeOffset LastWriteTime
{
get
{
return _lastModified;
}
set
{
ThrowIfInvalidArchive();
if (_archive.Mode == ZipArchiveMode.Read)
throw new NotSupportedException(SR.ReadOnlyArchive);
if (_archive.Mode == ZipArchiveMode.Create && _everOpenedForWrite)
throw new IOException(SR.FrozenAfterWrite);
if (value.DateTime.Year < ZipHelper.ValidZipDate_YearMin || value.DateTime.Year > ZipHelper.ValidZipDate_YearMax)
throw new ArgumentOutOfRangeException(nameof(value), SR.DateTimeOutOfRange);
_lastModified = value;
}
}
/// <summary>
/// The uncompressed size of the entry. This property is not valid in Create mode, and it is only valid in Update mode if the entry has not been opened.
/// </summary>
/// <exception cref="InvalidOperationException">This property is not available because the entry has been written to or modified.</exception>
public long Length
{
get
{
if (_everOpenedForWrite)
throw new InvalidOperationException(SR.LengthAfterWrite);
return _uncompressedSize;
}
}
/// <summary>
/// The filename of the entry. This is equivalent to the substring of Fullname that follows the final directory separator character.
/// </summary>
public string Name => ParseFileName(FullName, _versionMadeByPlatform);
/// <summary>
/// Deletes the entry from the archive.
/// </summary>
/// <exception cref="IOException">The entry is already open for reading or writing.</exception>
/// <exception cref="NotSupportedException">The ZipArchive that this entry belongs to was opened in a mode other than ZipArchiveMode.Update. </exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public void Delete()
{
if (_archive == null)
return;
if (_currentlyOpenForWrite)
throw new IOException(SR.DeleteOpenEntry);
if (_archive.Mode != ZipArchiveMode.Update)
throw new NotSupportedException(SR.DeleteOnlyInUpdate);
_archive.ThrowIfDisposed();
_archive.RemoveEntry(this);
_archive = null!;
UnloadStreams();
}
/// <summary>
/// Opens the entry. If the archive that the entry belongs to was opened in Read mode, the returned stream will be readable, and it may or may not be seekable. If Create mode, the returned stream will be writable and not seekable. If Update mode, the returned stream will be readable, writable, seekable, and support SetLength.
/// </summary>
/// <returns>A Stream that represents the contents of the entry.</returns>
/// <exception cref="IOException">The entry is already currently open for writing. -or- The entry has been deleted from the archive. -or- The archive that this entry belongs to was opened in ZipArchiveMode.Create, and this entry has already been written to once.</exception>
/// <exception cref="InvalidDataException">The entry is missing from the archive or is corrupt and cannot be read. -or- The entry has been compressed using a compression method that is not supported.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive that this entry belongs to has been disposed.</exception>
public Stream Open()
{
ThrowIfInvalidArchive();
switch (_archive.Mode)
{
case ZipArchiveMode.Read:
return OpenInReadMode(checkOpenable: true);
case ZipArchiveMode.Create:
return OpenInWriteMode();
case ZipArchiveMode.Update:
default:
Debug.Assert(_archive.Mode == ZipArchiveMode.Update);
return OpenInUpdateMode();
}
}
/// <summary>
/// Returns the FullName of the entry.
/// </summary>
/// <returns>FullName of the entry</returns>
public override string ToString()
{
return FullName;
}
// Only allow opening ZipArchives with large ZipArchiveEntries in update mode when running in a 64-bit process.
// This is for compatibility with old behavior that threw an exception for all process bitnesses, because this
// will not work in a 32-bit process.
private static readonly bool s_allowLargeZipArchiveEntriesInUpdateMode = IntPtr.Size > 4;
internal bool EverOpenedForWrite => _everOpenedForWrite;
private long OffsetOfCompressedData
{
get
{
if (_storedOffsetOfCompressedData == null)
{
Debug.Assert(_archive.ArchiveReader != null);
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
// by calling this, we are using local header _storedEntryNameBytes.Length and extraFieldLength
// to find start of data, but still using central directory size information
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
throw new InvalidDataException(SR.LocalFileHeaderCorrupt);
_storedOffsetOfCompressedData = _archive.ArchiveStream.Position;
}
return _storedOffsetOfCompressedData.Value;
}
}
private MemoryStream UncompressedData
{
get
{
if (_storedUncompressedData == null)
{
// this means we have never opened it before
// if _uncompressedSize > int.MaxValue, it's still okay, because MemoryStream will just
// grow as data is copied into it
_storedUncompressedData = new MemoryStream((int)_uncompressedSize);
if (_originallyInArchive)
{
using (Stream decompressor = OpenInReadMode(false))
{
try
{
decompressor.CopyTo(_storedUncompressedData);
}
catch (InvalidDataException)
{
// this is the case where the archive say the entry is deflate, but deflateStream
// throws an InvalidDataException. This property should only be getting accessed in
// Update mode, so we want to make sure _storedUncompressedData stays null so
// that later when we dispose the archive, this entry loads the compressedBytes, and
// copies them straight over
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
_currentlyOpenForWrite = false;
_everOpenedForWrite = false;
throw;
}
}
}
// if they start modifying it and the compression method is not "store", we should make sure it will get deflated
if (CompressionMethod != CompressionMethodValues.Stored)
{
CompressionMethod = CompressionMethodValues.Deflate;
}
}
return _storedUncompressedData;
}
}
private CompressionMethodValues CompressionMethod
{
get { return _storedCompressionMethod; }
set
{
if (value == CompressionMethodValues.Deflate)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate);
else if (value == CompressionMethodValues.Deflate64)
VersionToExtractAtLeast(ZipVersionNeededValues.Deflate64);
_storedCompressionMethod = value;
}
}
// does almost everything you need to do to forget about this entry
// writes the local header/data, gets rid of all the data,
// closes all of the streams except for the very outermost one that
// the user holds on to and is responsible for closing
//
// after calling this, and only after calling this can we be guaranteed
// that we are reading to write the central directory
//
// should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteAndFinishLocalEntry()
{
CloseStreams();
WriteLocalFileHeaderAndDataIfNeeded();
UnloadStreams();
}
// should only throw an exception in extremely exceptional cases because it is called from dispose
internal void WriteCentralDirectoryFileHeader()
{
// This part is simple, because we should definitely know the sizes by this time
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
// reading in should not be able to produce an entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = default;
uint compressedSizeTruncated, uncompressedSizeTruncated, offsetOfLocalHeaderTruncated;
bool zip64Needed = false;
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
// If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
}
else
{
compressedSizeTruncated = (uint)_compressedSize;
uncompressedSizeTruncated = (uint)_uncompressedSize;
}
if (_offsetOfLocalHeader > uint.MaxValue
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
)
{
zip64Needed = true;
offsetOfLocalHeaderTruncated = ZipHelper.Mask32Bit;
// If we have one of the sizes, the other must go in there as speced for LH, but not necessarily for CH, but we do it anyways
zip64ExtraField.LocalHeaderOffset = _offsetOfLocalHeader;
}
else
{
offsetOfLocalHeaderTruncated = (uint)_offsetOfLocalHeader;
}
if (zip64Needed)
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
// determine if we can fit zip64 extra field and original extra fields all in
int bigExtraFieldLength = (zip64Needed ? zip64ExtraField.TotalSize : 0)
+ (_cdUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_cdUnknownExtraFields) : 0);
ushort extraFieldLength;
if (bigExtraFieldLength > ushort.MaxValue)
{
extraFieldLength = (ushort)(zip64Needed ? zip64ExtraField.TotalSize : 0);
_cdUnknownExtraFields = null;
}
else
{
extraFieldLength = (ushort)bigExtraFieldLength;
}
writer.Write(ZipCentralDirectoryFileHeader.SignatureConstant); // Central directory file header signature (4 bytes)
writer.Write((byte)_versionMadeBySpecification); // Version made by Specification (version) (1 byte)
writer.Write((byte)CurrentZipPlatform); // Version made by Compatibility (type) (1 byte)
writer.Write((ushort)_versionToExtract); // Minimum version needed to extract (2 bytes)
writer.Write((ushort)_generalPurposeBitFlag); // General Purpose bit flag (2 bytes)
writer.Write((ushort)CompressionMethod); // The Compression method (2 bytes)
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // File last modification time and date (4 bytes)
writer.Write(_crc32); // CRC-32 (4 bytes)
writer.Write(compressedSizeTruncated); // Compressed Size (4 bytes)
writer.Write(uncompressedSizeTruncated); // Uncompressed Size (4 bytes)
writer.Write((ushort)_storedEntryNameBytes.Length); // File Name Length (2 bytes)
writer.Write(extraFieldLength); // Extra Field Length (2 bytes)
Debug.Assert(_fileComment.Length <= ushort.MaxValue);
writer.Write((ushort)_fileComment.Length);
writer.Write((ushort)0); // disk number start
writer.Write((ushort)0); // internal file attributes
writer.Write(_externalFileAttr); // external file attributes
writer.Write(offsetOfLocalHeaderTruncated); // offset of local header
writer.Write(_storedEntryNameBytes);
// write extra fields
if (zip64Needed)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_cdUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_cdUnknownExtraFields, _archive.ArchiveStream);
if (_fileComment.Length > 0)
writer.Write(_fileComment);
}
// returns false if fails, will get called on every entry before closing in update mode
// can throw InvalidDataException
internal bool LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded()
{
// we should have made this exact call in _archive.Init through ThrowIfOpenable
Debug.Assert(IsOpenable(false, true, out _));
// load local header's extra fields. it will be null if we couldn't read for some reason
if (_originallyInArchive)
{
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
Debug.Assert(_archive.ArchiveReader != null);
_lhUnknownExtraFields = ZipLocalFileHeader.GetExtraFields(_archive.ArchiveReader);
}
if (!_everOpenedForWrite && _originallyInArchive)
{
// we know that it is openable at this point
int MaxSingleBufferSize = Array.MaxLength;
_compressedBytes = new byte[(_compressedSize / MaxSingleBufferSize) + 1][];
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
_compressedBytes[i] = new byte[MaxSingleBufferSize];
}
_compressedBytes[_compressedBytes.Length - 1] = new byte[_compressedSize % MaxSingleBufferSize];
_archive.ArchiveStream.Seek(OffsetOfCompressedData, SeekOrigin.Begin);
for (int i = 0; i < _compressedBytes.Length - 1; i++)
{
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[i], MaxSingleBufferSize);
}
ZipHelper.ReadBytes(_archive.ArchiveStream, _compressedBytes[_compressedBytes.Length - 1], (int)(_compressedSize % MaxSingleBufferSize));
}
return true;
}
internal void ThrowIfNotOpenable(bool needToUncompress, bool needToLoadIntoMemory)
{
if (!IsOpenable(needToUncompress, needToLoadIntoMemory, out string? message))
throw new InvalidDataException(message);
}
private void DetectEntryNameVersion()
{
if (ParseFileName(_storedEntryName, _versionMadeByPlatform) == "")
{
VersionToExtractAtLeast(ZipVersionNeededValues.ExplicitDirectory);
}
}
private CheckSumAndSizeWriteStream GetDataCompressor(Stream backingStream, bool leaveBackingStreamOpen, EventHandler? onClose)
{
// stream stack: backingStream -> DeflateStream -> CheckSumWriteStream
// By default we compress with deflate, except if compression level is set to NoCompression then stored is used.
// Stored is also used for empty files, but we don't actually call through this function for that - we just write the stored value in the header
// Deflate64 is not supported on all platforms
Debug.Assert(CompressionMethod == CompressionMethodValues.Deflate
|| CompressionMethod == CompressionMethodValues.Stored);
bool isIntermediateStream = true;
Stream compressorStream;
switch (CompressionMethod)
{
case CompressionMethodValues.Stored:
compressorStream = backingStream;
isIntermediateStream = false;
break;
case CompressionMethodValues.Deflate:
case CompressionMethodValues.Deflate64:
default:
compressorStream = new DeflateStream(backingStream, _compressionLevel ?? CompressionLevel.Optimal, leaveBackingStreamOpen);
break;
}
bool leaveCompressorStreamOpenOnClose = leaveBackingStreamOpen && !isIntermediateStream;
var checkSumStream = new CheckSumAndSizeWriteStream(
compressorStream,
backingStream,
leaveCompressorStreamOpenOnClose,
this,
onClose,
(long initialPosition, long currentPosition, uint checkSum, Stream backing, ZipArchiveEntry thisRef, EventHandler? closeHandler) =>
{
thisRef._crc32 = checkSum;
thisRef._uncompressedSize = currentPosition;
thisRef._compressedSize = backing.Position - initialPosition;
closeHandler?.Invoke(thisRef, EventArgs.Empty);
});
return checkSumStream;
}
private Stream GetDataDecompressor(Stream compressedStreamToRead)
{
Stream? uncompressedStream;
switch (CompressionMethod)
{
case CompressionMethodValues.Deflate:
uncompressedStream = new DeflateStream(compressedStreamToRead, CompressionMode.Decompress, _uncompressedSize);
break;
case CompressionMethodValues.Deflate64:
uncompressedStream = new DeflateManagedStream(compressedStreamToRead, CompressionMethodValues.Deflate64, _uncompressedSize);
break;
case CompressionMethodValues.Stored:
default:
// we can assume that only deflate/deflate64/stored are allowed because we assume that
// IsOpenable is checked before this function is called
Debug.Assert(CompressionMethod == CompressionMethodValues.Stored);
uncompressedStream = compressedStreamToRead;
break;
}
return uncompressedStream;
}
private Stream OpenInReadMode(bool checkOpenable)
{
if (checkOpenable)
ThrowIfNotOpenable(needToUncompress: true, needToLoadIntoMemory: false);
Stream compressedStream = new SubReadStream(_archive.ArchiveStream, OffsetOfCompressedData, _compressedSize);
return GetDataDecompressor(compressedStream);
}
private Stream OpenInWriteMode()
{
if (_everOpenedForWrite)
throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime);
// we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed
_archive.DebugAssertIsStillArchiveStreamOwner(this);
_everOpenedForWrite = true;
CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true, (object? o, EventArgs e) =>
{
// release the archive stream
var entry = (ZipArchiveEntry)o!;
entry._archive.ReleaseArchiveStream(entry);
entry._outstandingWriteStream = null;
});
_outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this);
return new WrappedStream(baseStream: _outstandingWriteStream, closeBaseStream: true);
}
private Stream OpenInUpdateMode()
{
if (_currentlyOpenForWrite)
throw new IOException(SR.UpdateModeOneStream);
ThrowIfNotOpenable(needToUncompress: true, needToLoadIntoMemory: true);
_everOpenedForWrite = true;
_currentlyOpenForWrite = true;
// always put it at the beginning for them
UncompressedData.Seek(0, SeekOrigin.Begin);
return new WrappedStream(UncompressedData, this, thisRef =>
{
// once they close, we know uncompressed length, but still not compressed length
// so we don't fill in any size information
// those fields get figured out when we call GetCompressor as we write it to
// the actual archive
thisRef!._currentlyOpenForWrite = false;
});
}
private bool IsOpenable(bool needToUncompress, bool needToLoadIntoMemory, out string? message)
{
message = null;
if (_originallyInArchive)
{
if (needToUncompress)
{
if (CompressionMethod != CompressionMethodValues.Stored &&
CompressionMethod != CompressionMethodValues.Deflate &&
CompressionMethod != CompressionMethodValues.Deflate64)
{
switch (CompressionMethod)
{
case CompressionMethodValues.BZip2:
case CompressionMethodValues.LZMA:
message = SR.Format(SR.UnsupportedCompressionMethod, CompressionMethod.ToString());
break;
default:
message = SR.UnsupportedCompression;
break;
}
return false;
}
}
if (_diskNumberStart != _archive.NumberOfThisDisk)
{
message = SR.SplitSpanned;
return false;
}
if (_offsetOfLocalHeader > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
Debug.Assert(_archive.ArchiveReader != null);
_archive.ArchiveStream.Seek(_offsetOfLocalHeader, SeekOrigin.Begin);
if (!ZipLocalFileHeader.TrySkipBlock(_archive.ArchiveReader))
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
// when this property gets called, some duplicated work
if (OffsetOfCompressedData + _compressedSize > _archive.ArchiveStream.Length)
{
message = SR.LocalFileHeaderCorrupt;
return false;
}
// This limitation originally existed because a) it is unreasonable to load > 4GB into memory
// but also because the stream reading functions make it hard. This has been updated to handle
// this scenario in a 64-bit process using multiple buffers, delivered first as an OOB for
// compatibility.
if (needToLoadIntoMemory)
{
if (_compressedSize > int.MaxValue)
{
if (!s_allowLargeZipArchiveEntriesInUpdateMode)
{
message = SR.EntryTooLarge;
return false;
}
}
}
}
return true;
}
private bool SizesTooLarge() => _compressedSize > uint.MaxValue || _uncompressedSize > uint.MaxValue;
// return value is true if we allocated an extra field for 64 bit headers, un/compressed size
private bool WriteLocalFileHeader(bool isEmptyFile)
{
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
// _entryname only gets set when we read in or call moveTo. MoveTo does a check, and
// reading in should not be able to produce an entryname longer than ushort.MaxValue
Debug.Assert(_storedEntryNameBytes.Length <= ushort.MaxValue);
// decide if we need the Zip64 extra field:
Zip64ExtraField zip64ExtraField = default;
bool zip64Used = false;
uint compressedSizeTruncated, uncompressedSizeTruncated;
// if we already know that we have an empty file don't worry about anything, just do a straight shot of the header
if (isEmptyFile)
{
CompressionMethod = CompressionMethodValues.Stored;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
Debug.Assert(_compressedSize == 0);
Debug.Assert(_uncompressedSize == 0);
Debug.Assert(_crc32 == 0);
}
else
{
// if we have a non-seekable stream, don't worry about sizes at all, and just set the right bit
// if we are using the data descriptor, then sizes and crc should be set to 0 in the header
if (_archive.Mode == ZipArchiveMode.Create && _archive.ArchiveStream.CanSeek == false)
{
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
zip64Used = false;
compressedSizeTruncated = 0;
uncompressedSizeTruncated = 0;
// the crc should not have been set if we are in create mode, but clear it just to be sure
Debug.Assert(_crc32 == 0);
}
else // if we are not in streaming mode, we have to decide if we want to write zip64 headers
{
// We are in seekable mode so we will not need to write a data descriptor
_generalPurposeBitFlag &= ~BitFlagValues.DataDescriptor;
if (SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| (_archive._forceZip64 && _archive.Mode == ZipArchiveMode.Update)
#endif
)
{
zip64Used = true;
compressedSizeTruncated = ZipHelper.Mask32Bit;
uncompressedSizeTruncated = ZipHelper.Mask32Bit;
// prepare Zip64 extra field object. If we have one of the sizes, the other must go in there
zip64ExtraField.CompressedSize = _compressedSize;
zip64ExtraField.UncompressedSize = _uncompressedSize;
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
}
else
{
zip64Used = false;
compressedSizeTruncated = (uint)_compressedSize;
uncompressedSizeTruncated = (uint)_uncompressedSize;
}
}
}
// save offset
_offsetOfLocalHeader = writer.BaseStream.Position;
// calculate extra field. if zip64 stuff + original extraField aren't going to fit, dump the original extraField, because this is more important
int bigExtraFieldLength = (zip64Used ? zip64ExtraField.TotalSize : 0)
+ (_lhUnknownExtraFields != null ? ZipGenericExtraField.TotalSize(_lhUnknownExtraFields) : 0);
ushort extraFieldLength;
if (bigExtraFieldLength > ushort.MaxValue)
{
extraFieldLength = (ushort)(zip64Used ? zip64ExtraField.TotalSize : 0);
_lhUnknownExtraFields = null;
}
else
{
extraFieldLength = (ushort)bigExtraFieldLength;
}
// write header
writer.Write(ZipLocalFileHeader.SignatureConstant);
writer.Write((ushort)_versionToExtract);
writer.Write((ushort)_generalPurposeBitFlag);
writer.Write((ushort)CompressionMethod);
writer.Write(ZipHelper.DateTimeToDosTime(_lastModified.DateTime)); // uint
writer.Write(_crc32); // uint
writer.Write(compressedSizeTruncated); // uint
writer.Write(uncompressedSizeTruncated); // uint
writer.Write((ushort)_storedEntryNameBytes.Length);
writer.Write(extraFieldLength); // ushort
writer.Write(_storedEntryNameBytes);
if (zip64Used)
zip64ExtraField.WriteBlock(_archive.ArchiveStream);
if (_lhUnknownExtraFields != null)
ZipGenericExtraField.WriteAllBlocks(_lhUnknownExtraFields, _archive.ArchiveStream);
return zip64Used;
}
private void WriteLocalFileHeaderAndDataIfNeeded()
{
// _storedUncompressedData gets frozen here, and is what gets written to the file
if (_storedUncompressedData != null || _compressedBytes != null)
{
if (_storedUncompressedData != null)
{
_uncompressedSize = _storedUncompressedData.Length;
//The compressor fills in CRC and sizes
//The DirectToArchiveWriterStream writes headers and such
using (Stream entryWriter = new DirectToArchiveWriterStream(
GetDataCompressor(_archive.ArchiveStream, true, null),
this))
{
_storedUncompressedData.Seek(0, SeekOrigin.Begin);
_storedUncompressedData.CopyTo(entryWriter);
_storedUncompressedData.Dispose();
_storedUncompressedData = null;
}
}
else
{
if (_uncompressedSize == 0)
{
// reset size to ensure proper central directory size header
_compressedSize = 0;
}
WriteLocalFileHeader(isEmptyFile: _uncompressedSize == 0);
// according to ZIP specs, zero-byte files MUST NOT include file data
if (_uncompressedSize != 0)
{
Debug.Assert(_compressedBytes != null);
foreach (byte[] compressedBytes in _compressedBytes)
{
_archive.ArchiveStream.Write(compressedBytes, 0, compressedBytes.Length);
}
}
}
}
else // there is no data in the file, but if we are in update mode, we still need to write a header
{
if (_archive.Mode == ZipArchiveMode.Update || !_everOpenedForWrite)
{
_everOpenedForWrite = true;
WriteLocalFileHeader(isEmptyFile: true);
}
}
}
// Using _offsetOfLocalHeader, seeks back to where CRC and sizes should be in the header,
// writes them, then seeks back to where you started
// Assumes that the stream is currently at the end of the data
private void WriteCrcAndSizesInLocalHeader(bool zip64HeaderUsed)
{
long finalPosition = _archive.ArchiveStream.Position;
BinaryWriter writer = new BinaryWriter(_archive.ArchiveStream);
bool zip64Needed = SizesTooLarge()
#if DEBUG_FORCE_ZIP64
|| _archive._forceZip64
#endif
;
bool pretendStreaming = zip64Needed && !zip64HeaderUsed;
uint compressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (uint)_compressedSize;
uint uncompressedSizeTruncated = zip64Needed ? ZipHelper.Mask32Bit : (uint)_uncompressedSize;
// first step is, if we need zip64, but didn't allocate it, pretend we did a stream write, because
// we can't go back and give ourselves the space that the extra field needs.
// we do this by setting the correct property in the bit flag to indicate we have a data descriptor
// and setting the version to Zip64 to indicate that descriptor contains 64-bit values
if (pretendStreaming)
{
VersionToExtractAtLeast(ZipVersionNeededValues.Zip64);
_generalPurposeBitFlag |= BitFlagValues.DataDescriptor;
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToVersionFromHeaderStart,
SeekOrigin.Begin);
writer.Write((ushort)_versionToExtract);
writer.Write((ushort)_generalPurposeBitFlag);
}
// next step is fill out the 32-bit size values in the normal header. we can't assume that
// they are correct. we also write the CRC
_archive.ArchiveStream.Seek(_offsetOfLocalHeader + ZipLocalFileHeader.OffsetToCrcFromHeaderStart,
SeekOrigin.Begin);
if (!pretendStreaming)
{
writer.Write(_crc32);