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
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//Zip Spec here: http://www.pkware.com/documents/casestudies/APPNOTE.TXT
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.IO.Compression
{
public class ZipArchive : IDisposable
{
#region Fields
private Stream _archiveStream;
private ZipArchiveEntry _archiveStreamOwner;
private BinaryReader _archiveReader;
private ZipArchiveMode _mode;
private List<ZipArchiveEntry> _entries;
private ReadOnlyCollection<ZipArchiveEntry> _entriesCollection;
private Dictionary<String, ZipArchiveEntry> _entriesDictionary;
private Boolean _readEntries;
private Boolean _leaveOpen;
private Int64 _centralDirectoryStart; //only valid after ReadCentralDirectory
private Boolean _isDisposed;
private UInt32 _numberOfThisDisk; //only valid after ReadCentralDirectory
private Int64 _expectedNumberOfEntries;
private Stream _backingStream;
private Byte[] _archiveComment;
private Encoding _entryNameEncoding;
#if DEBUG_FORCE_ZIP64
public Boolean _forceZip64;
#endif
#endregion Fields
#region Public/Protected APIs
/// <summary>
/// Initializes a new instance of ZipArchive on the given stream for reading.
/// </summary>
/// <exception cref="ArgumentException">The stream is already closed or does not support reading.</exception>
/// <exception cref="ArgumentNullException">The stream is null.</exception>
/// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip archive.</exception>
/// <param name="stream">The stream containing the archive to be read.</param>
public ZipArchive(Stream stream) : this(stream, ZipArchiveMode.Read, leaveOpen: false, entryNameEncoding: null) { }
/// <summary>
/// Initializes a new instance of ZipArchive on the given stream in the specified mode.
/// </summary>
/// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
/// <exception cref="ArgumentNullException">The stream is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
/// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
/// <param name="stream">The input or output stream.</param>
/// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
public ZipArchive(Stream stream, ZipArchiveMode mode) : this(stream, mode, leaveOpen: false, entryNameEncoding: null) { }
/// <summary>
/// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open.
/// </summary>
/// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
/// <exception cref="ArgumentNullException">The stream is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
/// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
/// <param name="stream">The input or output stream.</param>
/// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
/// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param>
public ZipArchive(Stream stream, ZipArchiveMode mode, Boolean leaveOpen) : this(stream, mode, leaveOpen, entryNameEncoding: null) { }
/// <summary>
/// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open.
/// </summary>
/// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception>
/// <exception cref="ArgumentNullException">The stream is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception>
/// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception>
/// <param name="stream">The input or output stream.</param>
/// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param>
/// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param>
/// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive.
/// /// <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged.
/// However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support
/// UTF-8 encoding for entry names.<br />
/// This value is used as follows:</para>
/// <para><strong>Reading (opening) ZIP archive files:</strong></para>
/// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para>
/// <list>
/// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set,
/// use the current system default code page (<c>Encoding.Default</c>) in order to decode the entry name.</item>
/// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set,
/// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item>
/// </list>
/// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para>
/// <list>
/// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set,
/// use the specified <c>entryNameEncoding</c> in order to decode the entry name.</item>
/// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set,
/// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item>
/// </list>
/// <para><strong>Writing (saving) ZIP archive files:</strong></para>
/// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para>
/// <list>
/// <item>For entry names that contain characters outside the ASCII range,
/// the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header,
/// and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item>
/// <item>For entry names that do not contain characters outside the ASCII range,
/// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header,
/// and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item>
/// </list>
/// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para>
/// <list>
/// <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes.
/// The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only
/// if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item>
/// </list>
/// <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>,
/// otherwise an <see cref="ArgumentException"/> is thrown.</para>
/// </param>
/// <exception cref="ArgumentException">If a Unicode encoding other than UTF-8 is specified for the <code>entryNameEncoding</code>.</exception>
public ZipArchive(Stream stream, ZipArchiveMode mode, Boolean leaveOpen, Encoding entryNameEncoding)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
Contract.EndContractBlock();
this.EntryNameEncoding = entryNameEncoding;
this.Init(stream, mode, leaveOpen);
}
/// <summary>
/// The collection of entries that are currently in the ZipArchive. This may not accurately represent the actual entries that are present in the underlying file or stream.
/// </summary>
/// <exception cref="NotSupportedException">The ZipArchive does not support reading.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception>
/// <exception cref="InvalidDataException">The Zip archive is corrupt and the entries cannot be retrieved.</exception>
public ReadOnlyCollection<ZipArchiveEntry> Entries
{
get
{
Contract.Ensures(Contract.Result<ReadOnlyCollection<ZipArchiveEntry>>() != null);
if (_mode == ZipArchiveMode.Create)
throw new NotSupportedException(SR.EntriesInCreateMode);
ThrowIfDisposed();
EnsureCentralDirectoryRead();
return _entriesCollection;
}
}
/// <summary>
/// The ZipArchiveMode that the ZipArchive was initialized with.
/// </summary>
public ZipArchiveMode Mode
{
get
{
Contract.Ensures(
Contract.Result<ZipArchiveMode>() == ZipArchiveMode.Create
|| Contract.Result<ZipArchiveMode>() == ZipArchiveMode.Read
|| Contract.Result<ZipArchiveMode>() == ZipArchiveMode.Update);
return _mode;
}
}
/// <summary>
/// Creates an empty entry in the Zip archive with the specified entry name.
/// There are no restrictions on the names of entries.
/// The last write time of the entry is set to the current time.
/// If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.
/// Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression
/// algorithm will be used; the <code>ZipArchive</code> will not impose its own default.
/// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.)
/// </summary>
/// <exception cref="ArgumentException">entryName is a zero-length string.</exception>
/// <exception cref="ArgumentNullException">entryName is null.</exception>
/// <exception cref="NotSupportedException">The ZipArchive does not support writing.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception>
/// <param name="entryName">A path relative to the root of the archive, indicating the name of the entry to be created.</param>
/// <returns>A wrapper for the newly created file entry in the archive.</returns>
public ZipArchiveEntry CreateEntry(String entryName)
{
Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);
Contract.EndContractBlock();
return DoCreateEntry(entryName, null);
}
/// <summary>
/// Creates an empty entry in the Zip archive with the specified entry name. There are no restrictions on the names of entries. The last write time of the entry is set to the current time. If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name.
/// </summary>
/// <exception cref="ArgumentException">entryName is a zero-length string.</exception>
/// <exception cref="ArgumentNullException">entryName is null.</exception>
/// <exception cref="NotSupportedException">The ZipArchive does not support writing.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception>
/// <param name="entryName">A path relative to the root of the archive, indicating the name of the entry to be created.</param>
/// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param>
/// <returns>A wrapper for the newly created file entry in the archive.</returns>
public ZipArchiveEntry CreateEntry(String entryName, CompressionLevel compressionLevel)
{
Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);
Contract.EndContractBlock();
return DoCreateEntry(entryName, compressionLevel);
}
/// <summary>
/// Releases the unmanaged resources used by ZipArchive and optionally finishes writing the archive and releases the managed resources.
/// </summary>
/// <param name="disposing">true to finish writing the archive and release unmanaged and managed resources, false to release only unmanaged resources.</param>
protected virtual void Dispose(Boolean disposing)
{
if (disposing && !_isDisposed)
{
switch (_mode)
{
case ZipArchiveMode.Read:
break;
case ZipArchiveMode.Create:
case ZipArchiveMode.Update:
default:
Debug.Assert(_mode == ZipArchiveMode.Update || _mode == ZipArchiveMode.Create);
try
{
WriteFile();
}
catch (InvalidDataException)
{
CloseStreams();
_isDisposed = true;
throw;
}
break;
}
CloseStreams();
_isDisposed = true;
}
}
/// <summary>
/// Finishes writing the archive and releases all resources used by the ZipArchive object, unless the object was constructed with leaveOpen as true. Any streams from opened entries in the ZipArchive still open will throw exceptions on subsequent writes, as the underlying streams will have been closed.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Retrieves a wrapper for the file entry in the archive with the specified name. Names are compared using ordinal comparison. If there are multiple entries in the archive with the specified name, the first one found will be returned.
/// </summary>
/// <exception cref="ArgumentException">entryName is a zero-length string.</exception>
/// <exception cref="ArgumentNullException">entryName is null.</exception>
/// <exception cref="NotSupportedException">The ZipArchive does not support reading.</exception>
/// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception>
/// <exception cref="InvalidDataException">The Zip archive is corrupt and the entries cannot be retrieved.</exception>
/// <param name="entryName">A path relative to the root of the archive, identifying the desired entry.</param>
/// <returns>A wrapper for the file entry in the archive. If no entry in the archive exists with the specified name, null will be returned.</returns>
public ZipArchiveEntry GetEntry(String entryName)
{
if (entryName == null)
throw new ArgumentNullException(nameof(entryName));
Contract.EndContractBlock();
if (_mode == ZipArchiveMode.Create)
throw new NotSupportedException(SR.EntriesInCreateMode);
EnsureCentralDirectoryRead();
ZipArchiveEntry result;
_entriesDictionary.TryGetValue(entryName, out result);
return result;
}
#endregion Public/Protected APIs
#region Privates
internal BinaryReader ArchiveReader { get { return _archiveReader; } }
internal Stream ArchiveStream { get { return _archiveStream; } }
internal UInt32 NumberOfThisDisk { get { return _numberOfThisDisk; } }
internal Encoding EntryNameEncoding
{
get { return _entryNameEncoding; }
private set
{
// value == null is fine. This means the user does not want to overwrite default encoding picking logic.
// The Zip file spec [http://www.pkware.com/documents/casestudies/APPNOTE.TXT] specifies a bit in the entry header
// (specifically: the language encoding flag (EFS) in the general purpose bit flag of the local file header) that
// basically says: UTF8 (1) or CP437 (0). But in reality, tools replace CP437 with "something else that is not UTF8".
// For instance, the Windows Shell Zip tool takes "something else" to mean "the local system codepage".
// We default to the same behaviour, but we let the user explicitly specify the encoding to use for cases where they
// understand their use case well enough.
// Since the definition of acceptable encodings for the "something else" case is in reality by convention, it is not
// immediately clear, whether non-UTF8 Unicode encodings are acceptable. To determine that we would need to survey
// what is currently being done in the field, but we do not have the time for it right now.
// So, we artificially disallow non-UTF8 Unicode encodings for now to make sure we are not creating a compat burden
// for something other tools do not support. If we realise in future that "something else" should include non-UTF8
// Unicode encodings, we can remove this restriction.
if (value != null &&
(value.Equals(Encoding.BigEndianUnicode)
|| value.Equals(Encoding.Unicode)
#if FEATURE_UTF32
|| value.Equals(Encoding.UTF32)
#endif // FEATURE_UTF32
#if FEATURE_UTF7
|| value.Equals(Encoding.UTF7)
#endif // FEATURE_UTF7
))
{
throw new ArgumentException(SR.EntryNameEncodingNotSupported, nameof(EntryNameEncoding));
}
_entryNameEncoding = value;
}
}
private ZipArchiveEntry DoCreateEntry(String entryName, CompressionLevel? compressionLevel)
{
Contract.Ensures(Contract.Result<ZipArchiveEntry>() != null);
if (entryName == null)
throw new ArgumentNullException(nameof(entryName));
if (String.IsNullOrEmpty(entryName))
throw new ArgumentException(SR.CannotBeEmpty, nameof(entryName));
if (_mode == ZipArchiveMode.Read)
throw new NotSupportedException(SR.CreateInReadMode);
ThrowIfDisposed();
ZipArchiveEntry entry = compressionLevel.HasValue
? new ZipArchiveEntry(this, entryName, compressionLevel.Value)
: new ZipArchiveEntry(this, entryName);
AddEntry(entry);
return entry;
}
internal void AcquireArchiveStream(ZipArchiveEntry entry)
{
//if a previous entry had held the stream but never wrote anything, we write their local header for them
if (_archiveStreamOwner != null)
{
if (!_archiveStreamOwner.EverOpenedForWrite)
{
_archiveStreamOwner.WriteAndFinishLocalEntry();
}
else
{
throw new IOException(SR.CreateModeCreateEntryWhileOpen);
}
}
_archiveStreamOwner = entry;
}
private void AddEntry(ZipArchiveEntry entry)
{
_entries.Add(entry);
String entryName = entry.FullName;
if (!_entriesDictionary.ContainsKey(entryName))
{
_entriesDictionary.Add(entryName, entry);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This code is used in a contract check.")]
internal Boolean IsStillArchiveStreamOwner(ZipArchiveEntry entry)
{
return _archiveStreamOwner == entry;
}
internal void ReleaseArchiveStream(ZipArchiveEntry entry)
{
Debug.Assert(_archiveStreamOwner == entry);
_archiveStreamOwner = null;
}
internal void RemoveEntry(ZipArchiveEntry entry)
{
_entries.Remove(entry);
_entriesDictionary.Remove(entry.FullName);
}
internal void ThrowIfDisposed()
{
if (_isDisposed)
throw new ObjectDisposedException(this.GetType().ToString());
}
private void CloseStreams()
{
if (!_leaveOpen)
{
_archiveStream.Dispose();
if (_backingStream != null)
_backingStream.Dispose();
if (_archiveReader != null)
_archiveReader.Dispose();
}
else
{
/* if _backingStream isn't null, that means we assigned the original stream they passed
* us to _backingStream (which they requested we leave open), and _archiveStream was
* the temporary copy that we needed
*/
if (_backingStream != null)
_archiveStream.Dispose();
}
}
private void EnsureCentralDirectoryRead()
{
if (!_readEntries)
{
ReadCentralDirectory();
_readEntries = true;
}
}
private void Init(Stream stream, ZipArchiveMode mode, Boolean leaveOpen)
{
Stream extraTempStream = null;
try
{
_backingStream = null;
//check stream against mode
switch (mode)
{
case ZipArchiveMode.Create:
if (!stream.CanWrite)
throw new ArgumentException(SR.CreateModeCapabilities);
break;
case ZipArchiveMode.Read:
if (!stream.CanRead)
throw new ArgumentException(SR.ReadModeCapabilities);
if (!stream.CanSeek)
{
_backingStream = stream;
extraTempStream = stream = new MemoryStream();
_backingStream.CopyTo(stream);
stream.Seek(0, SeekOrigin.Begin);
}
break;
case ZipArchiveMode.Update:
if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek)
throw new ArgumentException(SR.UpdateModeCapabilities);
break;
default:
//still have to throw this, because stream constructor doesn't do mode argument checks
throw new ArgumentOutOfRangeException(nameof(mode));
}
_mode = mode;
_archiveStream = stream;
_archiveStreamOwner = null;
if (mode == ZipArchiveMode.Create)
_archiveReader = null;
else
_archiveReader = new BinaryReader(stream);
_entries = new List<ZipArchiveEntry>();
_entriesCollection = new ReadOnlyCollection<ZipArchiveEntry>(_entries);
_entriesDictionary = new Dictionary<String, ZipArchiveEntry>();
_readEntries = false;
_leaveOpen = leaveOpen;
_centralDirectoryStart = 0; //invalid until ReadCentralDirectory
_isDisposed = false;
_numberOfThisDisk = 0; //invalid until ReadCentralDirectory
_archiveComment = null;
switch (mode)
{
case ZipArchiveMode.Create:
_readEntries = true;
break;
case ZipArchiveMode.Read:
ReadEndOfCentralDirectory();
break;
case ZipArchiveMode.Update:
default:
Debug.Assert(mode == ZipArchiveMode.Update);
if (_archiveStream.Length == 0)
{
_readEntries = true;
}
else
{
ReadEndOfCentralDirectory();
EnsureCentralDirectoryRead();
foreach (ZipArchiveEntry entry in _entries)
{
entry.ThrowIfNotOpenable(false, true);
}
}
break;
}
}
catch
{
if (extraTempStream != null)
extraTempStream.Dispose();
throw;
}
}
private void ReadCentralDirectory()
{
try
{
//assume ReadEndOfCentralDirectory has been called and has populated _centralDirectoryStart
_archiveStream.Seek(_centralDirectoryStart, SeekOrigin.Begin);
Int64 numberOfEntries = 0;
//read the central directory
ZipCentralDirectoryFileHeader currentHeader;
Boolean saveExtraFieldsAndComments = Mode == ZipArchiveMode.Update;
while (ZipCentralDirectoryFileHeader.TryReadBlock(_archiveReader,
saveExtraFieldsAndComments, out currentHeader))
{
AddEntry(new ZipArchiveEntry(this, currentHeader));
numberOfEntries++;
}
if (numberOfEntries != _expectedNumberOfEntries)
throw new InvalidDataException(SR.NumEntriesWrong);
}
catch (EndOfStreamException ex)
{
throw new InvalidDataException(SR.Format(SR.CentralDirectoryInvalid, ex));
}
}
//This function reads all the EOCD stuff it needs to find the offset to the start of the central directory
//This offset gets put in _centralDirectoryStart and the number of this disk gets put in _numberOfThisDisk
//Also does some verification that this isn't a split/spanned archive
//Also checks that offset to CD isn't out of bounds
private void ReadEndOfCentralDirectory()
{
try
{
//this seeks to the start of the end of central directory record
_archiveStream.Seek(-ZipEndOfCentralDirectoryBlock.SizeOfBlockWithoutSignature, SeekOrigin.End);
if (!ZipHelper.SeekBackwardsToSignature(_archiveStream, ZipEndOfCentralDirectoryBlock.SignatureConstant))
throw new InvalidDataException(SR.EOCDNotFound);
Int64 eocdStart = _archiveStream.Position;
//read the EOCD
ZipEndOfCentralDirectoryBlock eocd;
Boolean eocdProper = ZipEndOfCentralDirectoryBlock.TryReadBlock(_archiveReader, out eocd);
Debug.Assert(eocdProper); //we just found this using the signature finder, so it should be okay
if (eocd.NumberOfThisDisk != eocd.NumberOfTheDiskWithTheStartOfTheCentralDirectory)
throw new InvalidDataException(SR.SplitSpanned);
_numberOfThisDisk = eocd.NumberOfThisDisk;
_centralDirectoryStart = eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber;
if (eocd.NumberOfEntriesInTheCentralDirectory != eocd.NumberOfEntriesInTheCentralDirectoryOnThisDisk)
throw new InvalidDataException(SR.SplitSpanned);
_expectedNumberOfEntries = eocd.NumberOfEntriesInTheCentralDirectory;
//only bother saving the comment if we are in update mode
if (_mode == ZipArchiveMode.Update)
_archiveComment = eocd.ArchiveComment;
//only bother looking for zip64 EOCD stuff if we suspect it is needed because some value is FFFFFFFFF
//because these are the only two values we need, we only worry about these
//if we don't find the zip64 EOCD, we just give up and try to use the original values
if (eocd.NumberOfThisDisk == ZipHelper.Mask16Bit
|| eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber == ZipHelper.Mask32Bit
|| eocd.NumberOfEntriesInTheCentralDirectory == ZipHelper.Mask16Bit)
{
//we need to look for zip 64 EOCD stuff
//seek to the zip 64 EOCD locator
_archiveStream.Seek(eocdStart - Zip64EndOfCentralDirectoryLocator.SizeOfBlockWithoutSignature, SeekOrigin.Begin);
//if we don't find it, assume it doesn't exist and use data from normal eocd
if (ZipHelper.SeekBackwardsToSignature(_archiveStream, Zip64EndOfCentralDirectoryLocator.SignatureConstant))
{
//use locator to get to Zip64EOCD
Zip64EndOfCentralDirectoryLocator locator;
Boolean zip64eocdLocatorProper = Zip64EndOfCentralDirectoryLocator.TryReadBlock(_archiveReader, out locator);
Debug.Assert(zip64eocdLocatorProper); //we just found this using the signature finder, so it should be okay
if (locator.OffsetOfZip64EOCD > (UInt64)Int64.MaxValue)
throw new InvalidDataException(SR.FieldTooBigOffsetToZip64EOCD);
Int64 zip64EOCDOffset = (Int64)locator.OffsetOfZip64EOCD;
_archiveStream.Seek(zip64EOCDOffset, SeekOrigin.Begin);
//read Zip64EOCD
Zip64EndOfCentralDirectoryRecord record;
if (!Zip64EndOfCentralDirectoryRecord.TryReadBlock(_archiveReader, out record))
throw new InvalidDataException(SR.Zip64EOCDNotWhereExpected);
_numberOfThisDisk = record.NumberOfThisDisk;
if (record.NumberOfEntriesTotal > (UInt64)Int64.MaxValue)
throw new InvalidDataException(SR.FieldTooBigNumEntries);
if (record.OffsetOfCentralDirectory > (UInt64)Int64.MaxValue)
throw new InvalidDataException(SR.FieldTooBigOffsetToCD);
if (record.NumberOfEntriesTotal != record.NumberOfEntriesOnThisDisk)
throw new InvalidDataException(SR.SplitSpanned);
_expectedNumberOfEntries = (Int64)record.NumberOfEntriesTotal;
_centralDirectoryStart = (Int64)record.OffsetOfCentralDirectory;
}
}
if (_centralDirectoryStart > _archiveStream.Length)
{
throw new InvalidDataException(SR.FieldTooBigOffsetToCD);
}
}
catch (EndOfStreamException ex)
{
throw new InvalidDataException(SR.CDCorrupt, ex);
}
catch (IOException ex)
{
throw new InvalidDataException(SR.CDCorrupt, ex);
}
}
//the only exceptions that this function will throw directly are InvalidDataExceptions
private void WriteFile()
{
//if we are in create mode, we always set readEntries to true in Init
//if we are in update mode, we call EnsureCentralDirectoryRead, which sets readEntries to true
Debug.Assert(_readEntries);
if (_mode == ZipArchiveMode.Update)
{
List<ZipArchiveEntry> markedForDelete = new List<ZipArchiveEntry>();
foreach (ZipArchiveEntry entry in _entries)
{
if (!entry.LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded())
markedForDelete.Add(entry);
}
foreach (ZipArchiveEntry entry in markedForDelete)
entry.Delete();
_archiveStream.Seek(0, SeekOrigin.Begin);
_archiveStream.SetLength(0);
//nothing after this should throw an exception
}
foreach (ZipArchiveEntry entry in _entries)
{
entry.WriteAndFinishLocalEntry();
}
Int64 startOfCentralDirectory = _archiveStream.Position;
foreach (ZipArchiveEntry entry in _entries)
{
entry.WriteCentralDirectoryFileHeader();
}
Int64 sizeOfCentralDirectory = _archiveStream.Position - startOfCentralDirectory;
WriteArchiveEpilogue(startOfCentralDirectory, sizeOfCentralDirectory);
}
//writes eocd, and if needed, zip 64 eocd, zip64 eocd locator
//should only throw an exception in extremely exceptional cases because it is called from dispose
private void WriteArchiveEpilogue(Int64 startOfCentralDirectory, Int64 sizeOfCentralDirectory)
{
//determine if we need Zip 64
Boolean needZip64 = false;
if (startOfCentralDirectory >= UInt32.MaxValue
|| sizeOfCentralDirectory >= UInt32.MaxValue
|| _entries.Count >= ZipHelper.Mask16Bit
#if DEBUG_FORCE_ZIP64
|| _forceZip64
#endif
)
needZip64 = true;
//if we need zip 64, write zip 64 eocd and locator
if (needZip64)
{
Int64 zip64EOCDRecordStart = _archiveStream.Position;
Zip64EndOfCentralDirectoryRecord.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory);
Zip64EndOfCentralDirectoryLocator.WriteBlock(_archiveStream, zip64EOCDRecordStart);
}
//write normal eocd
ZipEndOfCentralDirectoryBlock.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory, _archiveComment);
}
#endregion Privates
}
}
|