forked from svn2github/dotnetzip
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZipEntry.Write.cs
More file actions
2582 lines (2207 loc) · 114 KB
/
Copy pathZipEntry.Write.cs
File metadata and controls
2582 lines (2207 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
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
//#define Trace
// ZipEntry.Write.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: <2011-July-30 14:55:47>
//
// ------------------------------------------------------------------
//
// This module defines logic for writing (saving) the ZipEntry into a
// zip file.
//
// ------------------------------------------------------------------
using System;
using System.IO;
using RE = System.Text.RegularExpressions;
namespace Ionic.Zip
{
public partial class ZipEntry
{
internal void WriteCentralDirectoryEntry(Stream s)
{
byte[] bytes = new byte[4096];
int i = 0;
// signature
bytes[i++] = (byte)(ZipConstants.ZipDirEntrySignature & 0x000000FF);
bytes[i++] = (byte)((ZipConstants.ZipDirEntrySignature & 0x0000FF00) >> 8);
bytes[i++] = (byte)((ZipConstants.ZipDirEntrySignature & 0x00FF0000) >> 16);
bytes[i++] = (byte)((ZipConstants.ZipDirEntrySignature & 0xFF000000) >> 24);
// Version Made By
// workitem 7071
// We must not overwrite the VersionMadeBy field when writing out a zip
// archive. The VersionMadeBy tells the zip reader the meaning of the
// File attributes. Overwriting the VersionMadeBy will result in
// inconsistent metadata. Consider the scenario where the application
// opens and reads a zip file that had been created on Linux. Then the
// app adds one file to the Zip archive, and saves it. The file
// attributes for all the entries added on Linux will be significant for
// Linux. Therefore the VersionMadeBy for those entries must not be
// changed. Only the entries that are actually created on Windows NTFS
// should get the VersionMadeBy indicating Windows/NTFS.
bytes[i++] = (byte)(_VersionMadeBy & 0x00FF);
bytes[i++] = (byte)((_VersionMadeBy & 0xFF00) >> 8);
// Apparently we want to duplicate the extra field here; we cannot
// simply zero it out and assume tools and apps will use the right one.
////Int16 extraFieldLengthSave = (short)(_EntryHeader[28] + _EntryHeader[29] * 256);
////_EntryHeader[28] = 0;
////_EntryHeader[29] = 0;
// Version Needed, Bitfield, compression method, lastmod,
// crc, compressed and uncompressed sizes, filename length and extra field length.
// These are all present in the local file header, but they may be zero values there.
// So we cannot just copy them.
// workitem 11969: Version Needed To Extract in central directory must be
// the same as the local entry or MS .NET System.IO.Zip fails read.
Int16 vNeeded = (Int16)(VersionNeeded != 0 ? VersionNeeded : 20);
// workitem 12964
if (_OutputUsesZip64==null)
{
// a zipentry in a zipoutputstream, with zero bytes written
_OutputUsesZip64 = new Nullable<bool>(_container.Zip64 == Zip64Option.Always);
}
Int16 versionNeededToExtract = (Int16)(_OutputUsesZip64.Value ? 45 : vNeeded);
#if BZIP
if (this.CompressionMethod == Ionic.Zip.CompressionMethod.BZip2)
versionNeededToExtract = 46;
#endif
bytes[i++] = (byte)(versionNeededToExtract & 0x00FF);
bytes[i++] = (byte)((versionNeededToExtract & 0xFF00) >> 8);
bytes[i++] = (byte)(_BitField & 0x00FF);
bytes[i++] = (byte)((_BitField & 0xFF00) >> 8);
bytes[i++] = (byte)(_CompressionMethod & 0x00FF);
bytes[i++] = (byte)((_CompressionMethod & 0xFF00) >> 8);
#if AESCRYPTO
if (Encryption == EncryptionAlgorithm.WinZipAes128 ||
Encryption == EncryptionAlgorithm.WinZipAes256)
{
i -= 2;
bytes[i++] = 0x63;
bytes[i++] = 0;
}
#endif
bytes[i++] = (byte)(_TimeBlob & 0x000000FF);
bytes[i++] = (byte)((_TimeBlob & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_TimeBlob & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_TimeBlob & 0xFF000000) >> 24);
bytes[i++] = (byte)(_Crc32 & 0x000000FF);
bytes[i++] = (byte)((_Crc32 & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_Crc32 & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_Crc32 & 0xFF000000) >> 24);
int j = 0;
if (_OutputUsesZip64.Value)
{
// CompressedSize (Int32) and UncompressedSize - all 0xFF
for (j = 0; j < 8; j++)
bytes[i++] = 0xFF;
}
else
{
bytes[i++] = (byte)(_CompressedSize & 0x000000FF);
bytes[i++] = (byte)((_CompressedSize & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_CompressedSize & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_CompressedSize & 0xFF000000) >> 24);
bytes[i++] = (byte)(_UncompressedSize & 0x000000FF);
bytes[i++] = (byte)((_UncompressedSize & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_UncompressedSize & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_UncompressedSize & 0xFF000000) >> 24);
}
byte[] fileNameBytes = GetEncodedFileNameBytes();
Int16 filenameLength = (Int16)fileNameBytes.Length;
bytes[i++] = (byte)(filenameLength & 0x00FF);
bytes[i++] = (byte)((filenameLength & 0xFF00) >> 8);
// do this again because now we have real data
_presumeZip64 = _OutputUsesZip64.Value;
// workitem 11131
//
// cannot generate the extra field again, here's why: In the case of a
// zero-byte entry, which uses encryption, DotNetZip will "remove" the
// encryption from the entry. It does this in PostProcessOutput; it
// modifies the entry header, and rewrites it, resetting the Bitfield
// (one bit indicates encryption), and potentially resetting the
// compression method - for AES the Compression method is 0x63, and it
// would get reset to zero (no compression). It then calls SetLength()
// to truncate the stream to remove the encryption header (12 bytes for
// AES256). But, it leaves the previously-generated "Extra Field"
// metadata (11 bytes) for AES in the entry header. This extra field
// data is now "orphaned" - it refers to AES encryption when in fact no
// AES encryption is used. But no problem, the PKWARE spec says that
// unrecognized extra fields can just be ignored. ok. After "removal"
// of AES encryption, the length of the Extra Field can remains the
// same; it's just that there will be 11 bytes in there that previously
// pertained to AES which are now unused. Even the field code is still
// there, but it will be unused by readers, as the encryption bit is not
// set.
//
// Re-calculating the Extra field now would produce a block that is 11
// bytes shorter, and that mismatch - between the extra field in the
// local header and the extra field in the Central Directory - would
// cause problems. (where? why? what problems?) So we can't do
// that. It's all good though, because though the content may have
// changed, the length definitely has not. Also, the _EntryHeader
// contains the "updated" extra field (after PostProcessOutput) at
// offset (30 + filenameLength).
_Extra = ConstructExtraField(true);
Int16 extraFieldLength = (Int16)((_Extra == null) ? 0 : _Extra.Length);
bytes[i++] = (byte)(extraFieldLength & 0x00FF);
bytes[i++] = (byte)((extraFieldLength & 0xFF00) >> 8);
// File (entry) Comment Length
// the _CommentBytes private field was set during WriteHeader()
int commentLength = (_CommentBytes == null) ? 0 : _CommentBytes.Length;
// the size of our buffer defines the max length of the comment we can write
if (commentLength + i > bytes.Length) commentLength = bytes.Length - i;
bytes[i++] = (byte)(commentLength & 0x00FF);
bytes[i++] = (byte)((commentLength & 0xFF00) >> 8);
// Disk number start
bool segmented = (this._container.ZipFile != null) &&
(this._container.ZipFile.MaxOutputSegmentSize != 0);
if (segmented) // workitem 13915
{
// Emit nonzero disknumber only if saving segmented archive.
bytes[i++] = (byte)(_diskNumber & 0x00FF);
bytes[i++] = (byte)((_diskNumber & 0xFF00) >> 8);
}
else
{
// If reading a segmneted archive and saving to a regular archive,
// ZipEntry._diskNumber will be non-zero but it should be saved as
// zero.
bytes[i++] = 0;
bytes[i++] = 0;
}
// internal file attrs
// workitem 7801
bytes[i++] = (byte)((_IsText) ? 1 : 0); // lo bit: filetype hint. 0=bin, 1=txt.
bytes[i++] = 0;
// external file attrs
// workitem 7071
bytes[i++] = (byte)(_ExternalFileAttrs & 0x000000FF);
bytes[i++] = (byte)((_ExternalFileAttrs & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_ExternalFileAttrs & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_ExternalFileAttrs & 0xFF000000) >> 24);
// workitem 11131
// relative offset of local header.
//
// If necessary to go to 64-bit value, then emit 0xFFFFFFFF,
// else write out the value.
//
// Even if zip64 is required for other reasons - number of the entry
// > 65534, or uncompressed size of the entry > MAX_INT32, the ROLH
// need not be stored in a 64-bit field .
if (_RelativeOffsetOfLocalHeader > 0xFFFFFFFFL) // _OutputUsesZip64.Value
{
bytes[i++] = 0xFF;
bytes[i++] = 0xFF;
bytes[i++] = 0xFF;
bytes[i++] = 0xFF;
}
else
{
bytes[i++] = (byte)(_RelativeOffsetOfLocalHeader & 0x000000FF);
bytes[i++] = (byte)((_RelativeOffsetOfLocalHeader & 0x0000FF00) >> 8);
bytes[i++] = (byte)((_RelativeOffsetOfLocalHeader & 0x00FF0000) >> 16);
bytes[i++] = (byte)((_RelativeOffsetOfLocalHeader & 0xFF000000) >> 24);
}
// actual filename
Buffer.BlockCopy(fileNameBytes, 0, bytes, i, filenameLength);
i += filenameLength;
// "Extra field"
if (_Extra != null)
{
// workitem 11131
//
// copy from EntryHeader if available - it may have been updated.
// if not, copy from Extra. This would be unnecessary if I just
// updated the Extra field when updating EntryHeader, in
// PostProcessOutput.
//?? I don't understand why I wouldn't want to just use
// the recalculated Extra field. ??
// byte[] h = _EntryHeader ?? _Extra;
// int offx = (h == _EntryHeader) ? 30 + filenameLength : 0;
// Buffer.BlockCopy(h, offx, bytes, i, extraFieldLength);
// i += extraFieldLength;
byte[] h = _Extra;
int offx = 0;
Buffer.BlockCopy(h, offx, bytes, i, extraFieldLength);
i += extraFieldLength;
}
// file (entry) comment
if (commentLength != 0)
{
// now actually write the comment itself into the byte buffer
Buffer.BlockCopy(_CommentBytes, 0, bytes, i, commentLength);
// for (j = 0; (j < commentLength) && (i + j < bytes.Length); j++)
// bytes[i + j] = _CommentBytes[j];
i += commentLength;
}
s.Write(bytes, 0, i);
}
#if INFOZIP_UTF8
static private bool FileNameIsUtf8(char[] FileNameChars)
{
bool isUTF8 = false;
bool isUnicode = false;
for (int j = 0; j < FileNameChars.Length; j++)
{
byte[] b = System.BitConverter.GetBytes(FileNameChars[j]);
isUnicode |= (b.Length != 2);
isUnicode |= (b[1] != 0);
isUTF8 |= ((b[0] & 0x80) != 0);
}
return isUTF8;
}
#endif
private byte[] ConstructExtraField(bool forCentralDirectory)
{
var listOfBlocks = new System.Collections.Generic.List<byte[]>();
byte[] block;
// Conditionally emit an extra field with Zip64 information. If the
// Zip64 option is Always, we emit the field, before knowing that it's
// necessary. Later, if it turns out this entry does not need zip64,
// we'll set the header ID to rubbish and the data will be ignored.
// This results in additional overhead metadata in the zip file, but
// it will be small in comparison to the entry data.
//
// On the other hand if the Zip64 option is AsNecessary and it's NOT
// for the central directory, then we do the same thing. Or, if the
// Zip64 option is AsNecessary and it IS for the central directory,
// and the entry requires zip64, then emit the header.
if (_container.Zip64 == Zip64Option.Always ||
(_container.Zip64 == Zip64Option.AsNecessary &&
(!forCentralDirectory || _entryRequiresZip64.Value)))
{
// add extra field for zip64 here
// workitem 7924
int sz = 4 + (forCentralDirectory ? 28 : 16);
block = new byte[sz];
int i = 0;
if (_presumeZip64 || forCentralDirectory)
{
// HeaderId = always use zip64 extensions.
block[i++] = 0x01;
block[i++] = 0x00;
}
else
{
// HeaderId = dummy data now, maybe set to 0x0001 (ZIP64) later.
block[i++] = 0x99;
block[i++] = 0x99;
}
// DataSize
block[i++] = (byte)(sz - 4); // decimal 28 or 16 (workitem 7924)
block[i++] = 0x00;
// The actual metadata - we may or may not have real values yet...
// uncompressed size
Array.Copy(BitConverter.GetBytes(_UncompressedSize), 0, block, i, 8);
i += 8;
// compressed size
Array.Copy(BitConverter.GetBytes(_CompressedSize), 0, block, i, 8);
i += 8;
// workitem 7924 - only include this if the "extra" field is for
// use in the central directory. It is unnecessary and not useful
// for local header; makes WinZip choke.
if (forCentralDirectory)
{
// relative offset
Array.Copy(BitConverter.GetBytes(_RelativeOffsetOfLocalHeader), 0, block, i, 8);
i += 8;
// starting disk number
Array.Copy(BitConverter.GetBytes(0), 0, block, i, 4);
}
listOfBlocks.Add(block);
}
#if AESCRYPTO
if (Encryption == EncryptionAlgorithm.WinZipAes128 ||
Encryption == EncryptionAlgorithm.WinZipAes256)
{
block = new byte[4 + 7];
int i = 0;
// extra field for WinZip AES
// header id
block[i++] = 0x01;
block[i++] = 0x99;
// data size
block[i++] = 0x07;
block[i++] = 0x00;
// vendor number
block[i++] = 0x01; // AE-1 - means "Verify CRC"
block[i++] = 0x00;
// vendor id "AE"
block[i++] = 0x41;
block[i++] = 0x45;
// key strength
int keystrength = GetKeyStrengthInBits(Encryption);
if (keystrength == 128)
block[i] = 1;
else if (keystrength == 256)
block[i] = 3;
else
block[i] = 0xFF;
i++;
// actual compression method
block[i++] = (byte)(_CompressionMethod & 0x00FF);
block[i++] = (byte)(_CompressionMethod & 0xFF00);
listOfBlocks.Add(block);
}
#endif
if (_ntfsTimesAreSet && _emitNtfsTimes)
{
block = new byte[32 + 4];
// HeaderId 2 bytes 0x000a == NTFS times
// Datasize 2 bytes 32
// reserved 4 bytes ?? don't care
// timetag 2 bytes 0x0001 == NTFS time
// size 2 bytes 24 == 8 bytes each for ctime, mtime, atime
// mtime 8 bytes win32 ticks since win32epoch
// atime 8 bytes win32 ticks since win32epoch
// ctime 8 bytes win32 ticks since win32epoch
int i = 0;
// extra field for NTFS times
// header id
block[i++] = 0x0a;
block[i++] = 0x00;
// data size
block[i++] = 32;
block[i++] = 0;
i += 4; // reserved
// time tag
block[i++] = 0x01;
block[i++] = 0x00;
// data size (again)
block[i++] = 24;
block[i++] = 0;
Int64 z = _Mtime.ToFileTime();
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 8);
i += 8;
z = _Atime.ToFileTime();
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 8);
i += 8;
z = _Ctime.ToFileTime();
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 8);
i += 8;
listOfBlocks.Add(block);
}
if (_ntfsTimesAreSet && _emitUnixTimes)
{
int len = 5 + 4;
if (!forCentralDirectory) len += 8;
block = new byte[len];
// local form:
// --------------
// HeaderId 2 bytes 0x5455 == unix timestamp
// Datasize 2 bytes 13
// flags 1 byte 7 (low three bits all set)
// mtime 4 bytes seconds since unix epoch
// atime 4 bytes seconds since unix epoch
// ctime 4 bytes seconds since unix epoch
//
// central directory form:
//---------------------------------
// HeaderId 2 bytes 0x5455 == unix timestamp
// Datasize 2 bytes 5
// flags 1 byte 7 (low three bits all set)
// mtime 4 bytes seconds since unix epoch
//
int i = 0;
// extra field for "unix" times
// header id
block[i++] = 0x55;
block[i++] = 0x54;
// data size
block[i++] = unchecked((byte)(len - 4));
block[i++] = 0;
// flags
block[i++] = 0x07;
Int32 z = unchecked((int)((_Mtime - _unixEpoch).TotalSeconds));
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 4);
i += 4;
if (!forCentralDirectory)
{
z = unchecked((int)((_Atime - _unixEpoch).TotalSeconds));
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 4);
i += 4;
z = unchecked((int)((_Ctime - _unixEpoch).TotalSeconds));
Array.Copy(BitConverter.GetBytes(z), 0, block, i, 4);
i += 4;
}
listOfBlocks.Add(block);
}
// inject other blocks here...
// concatenate any blocks we've got:
byte[] aggregateBlock = null;
if (listOfBlocks.Count > 0)
{
int totalLength = 0;
int i, current = 0;
for (i = 0; i < listOfBlocks.Count; i++)
totalLength += listOfBlocks[i].Length;
aggregateBlock = new byte[totalLength];
for (i = 0; i < listOfBlocks.Count; i++)
{
System.Array.Copy(listOfBlocks[i], 0, aggregateBlock, current, listOfBlocks[i].Length);
current += listOfBlocks[i].Length;
}
}
return aggregateBlock;
}
// private System.Text.Encoding GenerateCommentBytes()
// {
// var getEncoding = new Func<System.Text.Encoding>({
// switch (AlternateEncodingUsage)
// {
// case ZipOption.Always:
// return AlternateEncoding;
// case ZipOption.Never:
// return ibm437;
// }
// var cb = ibm437.GetBytes(_Comment);
// // need to use this form of GetString() for .NET CF
// string s1 = ibm437.GetString(cb, 0, cb.Length);
// if (s1 == _Comment)
// return ibm437;
// return AlternateEncoding;
// });
//
// var encoding = getEncoding();
// _CommentBytes = encoding.GetBytes(_Comment);
// return encoding;
// }
private string NormalizeFileName()
{
// here, we need to flip the backslashes to forward-slashes,
// also, we need to trim the \\server\share syntax from any UNC path.
// and finally, we need to remove any leading .\
string SlashFixed = FileName.Replace("\\", "/");
string s1 = null;
if ((_TrimVolumeFromFullyQualifiedPaths) && (FileName.Length >= 3)
&& (FileName[1] == ':') && (SlashFixed[2] == '/'))
{
// trim off volume letter, colon, and slash
s1 = SlashFixed.Substring(3);
}
else if ((FileName.Length >= 4)
&& ((SlashFixed[0] == '/') && (SlashFixed[1] == '/')))
{
int n = SlashFixed.IndexOf('/', 2);
if (n == -1)
throw new ArgumentException("The path for that entry appears to be badly formatted");
s1 = SlashFixed.Substring(n + 1);
}
else if ((FileName.Length >= 3)
&& ((SlashFixed[0] == '.') && (SlashFixed[1] == '/')))
{
// trim off dot and slash
s1 = SlashFixed.Substring(2);
}
else
{
s1 = SlashFixed;
}
return s1;
}
/// <summary>
/// generate and return a byte array that encodes the filename
/// for the entry.
/// </summary>
/// <remarks>
/// <para>
/// side effects: generate and store into _CommentBytes the
/// byte array for any comment attached to the entry. Also
/// sets _actualEncoding to indicate the actual encoding
/// used. The same encoding is used for both filename and
/// comment.
/// </para>
/// </remarks>
private byte[] GetEncodedFileNameBytes()
{
// workitem 6513
var s1 = NormalizeFileName();
switch(AlternateEncodingUsage)
{
case ZipOption.Always:
if (!(_Comment == null || _Comment.Length == 0))
_CommentBytes = AlternateEncoding.GetBytes(_Comment);
_actualEncoding = AlternateEncoding;
return AlternateEncoding.GetBytes(s1);
case ZipOption.Never:
if (!(_Comment == null || _Comment.Length == 0))
_CommentBytes = ibm437.GetBytes(_Comment);
_actualEncoding = ibm437;
return ibm437.GetBytes(s1);
}
// arriving here means AlternateEncodingUsage is "AsNecessary"
// case ZipOption.AsNecessary:
// workitem 6513: when writing, use the alternative encoding
// only when _actualEncoding is not yet set (it can be set
// during Read), and when ibm437 will not do.
byte[] result = ibm437.GetBytes(s1);
// need to use this form of GetString() for .NET CF
string s2 = ibm437.GetString(result, 0, result.Length);
_CommentBytes = null;
if (s2 != s1)
{
// Encoding the filename with ibm437 does not allow round-trips.
// Therefore, use the alternate encoding. Assume it will work,
// no checking of round trips here.
result = AlternateEncoding.GetBytes(s1);
if (_Comment != null && _Comment.Length != 0)
_CommentBytes = AlternateEncoding.GetBytes(_Comment);
_actualEncoding = AlternateEncoding;
return result;
}
_actualEncoding = ibm437;
// Using ibm437, FileName can be encoded without information
// loss; now try the Comment.
// if there is no comment, use ibm437.
if (_Comment == null || _Comment.Length == 0)
return result;
// there is a comment. Get the encoded form.
byte[] cbytes = ibm437.GetBytes(_Comment);
string c2 = ibm437.GetString(cbytes,0,cbytes.Length);
// Check for round-trip.
if (c2 != Comment)
{
// Comment cannot correctly be encoded with ibm437. Use
// the alternate encoding.
result = AlternateEncoding.GetBytes(s1);
_CommentBytes = AlternateEncoding.GetBytes(_Comment);
_actualEncoding = AlternateEncoding;
return result;
}
// use IBM437
_CommentBytes = cbytes;
return result;
}
private bool WantReadAgain()
{
if (_UncompressedSize < 0x10) return false;
if (_CompressionMethod == 0x00) return false;
if (CompressionLevel == Ionic.Zlib.CompressionLevel.None) return false;
if (_CompressedSize < _UncompressedSize) return false;
if (this._Source == ZipEntrySource.Stream && !this._sourceStream.CanSeek) return false;
#if AESCRYPTO
if (_aesCrypto_forWrite != null && (CompressedSize - _aesCrypto_forWrite.SizeOfEncryptionMetadata) <= UncompressedSize + 0x10) return false;
#endif
if (_zipCrypto_forWrite != null && (CompressedSize - 12) <= UncompressedSize) return false;
return true;
}
private void MaybeUnsetCompressionMethodForWriting(int cycle)
{
// if we've already tried with compression... turn it off this time
if (cycle > 1)
{
_CompressionMethod = 0x0;
return;
}
// compression for directories = 0x00 (No Compression)
if (IsDirectory)
{
_CompressionMethod = 0x0;
return;
}
if (this._Source == ZipEntrySource.ZipFile)
{
return; // do nothing
}
// If __FileDataPosition is zero, then that means we will get the data
// from a file or stream.
// It is never possible to compress a zero-length file, so we check for
// this condition.
if (this._Source == ZipEntrySource.Stream)
{
// workitem 7742
if (_sourceStream != null && _sourceStream.CanSeek)
{
// Length prop will throw if CanSeek is false
long fileLength = _sourceStream.Length;
if (fileLength == 0)
{
_CompressionMethod = 0x00;
return;
}
}
}
else if ((this._Source == ZipEntrySource.FileSystem) && (SharedUtilities.GetFileLength(LocalFileName) == 0L))
{
_CompressionMethod = 0x00;
return;
}
// Ok, we're getting the data to be compressed from a
// non-zero-length file or stream, or a file or stream of
// unknown length, and we presume that it is non-zero. In
// that case we check the callback to see if the app wants
// to tell us whether to compress or not.
if (SetCompression != null)
CompressionLevel = SetCompression(LocalFileName, _FileNameInArchive);
// finally, set CompressionMethod to None if CompressionLevel is None
if (CompressionLevel == (short)Ionic.Zlib.CompressionLevel.None &&
CompressionMethod == Ionic.Zip.CompressionMethod.Deflate)
_CompressionMethod = 0x00;
return;
}
// write the header info for an entry
internal void WriteHeader(Stream s, int cycle)
{
// Must remember the offset, within the output stream, of this particular
// entry header.
//
// This is for 2 reasons:
//
// 1. so we can determine the RelativeOffsetOfLocalHeader (ROLH) for
// use in the central directory.
// 2. so we can seek backward in case there is an error opening or reading
// the file, and the application decides to skip the file. In this case,
// we need to seek backward in the output stream to allow the next entry
// to be added to the zipfile output stream.
//
// Normally you would just store the offset before writing to the output
// stream and be done with it. But the possibility to use split archives
// makes this approach ineffective. In split archives, each file or segment
// is bound to a max size limit, and each local file header must not span a
// segment boundary; it must be written contiguously. If it will fit in the
// current segment, then the ROLH is just the current Position in the output
// stream. If it won't fit, then we need a new file (segment) and the ROLH
// is zero.
//
// But we only can know if it is possible to write a header contiguously
// after we know the size of the local header, a size that varies with
// things like filename length, comments, and extra fields. We have to
// compute the header fully before knowing whether it will fit.
//
// That takes care of item #1 above. Now, regarding #2. If an error occurs
// while computing the local header, we want to just seek backward. The
// exception handling logic (in the caller of WriteHeader) uses ROLH to
// scroll back.
//
// All this means we have to preserve the starting offset before computing
// the header, and also we have to compute the offset later, to handle the
// case of split archives.
var counter = s as CountingStream;
// workitem 8098: ok (output)
// This may change later, for split archives
// Don't set _RelativeOffsetOfLocalHeader. Instead, set a temp variable.
// This allows for re-streaming, where a zip entry might be read from a
// zip archive (and maybe decrypted, and maybe decompressed) and then
// written to another zip archive, with different settings for
// compression method, compression level, or encryption algorithm.
_future_ROLH = (counter != null)
? counter.ComputedPosition
: s.Position;
int j = 0, i = 0;
byte[] block = new byte[30];
// signature
block[i++] = (byte)(ZipConstants.ZipEntrySignature & 0x000000FF);
block[i++] = (byte)((ZipConstants.ZipEntrySignature & 0x0000FF00) >> 8);
block[i++] = (byte)((ZipConstants.ZipEntrySignature & 0x00FF0000) >> 16);
block[i++] = (byte)((ZipConstants.ZipEntrySignature & 0xFF000000) >> 24);
// Design notes for ZIP64:
//
// The specification says that the header must include the Compressed
// and Uncompressed sizes, as well as the CRC32 value. When creating
// a zip via streamed processing, these quantities are not known until
// after the compression is done. Thus, a typical way to do it is to
// insert zeroes for these quantities, then do the compression, then
// seek back to insert the appropriate values, then seek forward to
// the end of the file data.
//
// There is also the option of using bit 3 in the GP bitfield - to
// specify that there is a data descriptor after the file data
// containing these three quantities.
//
// This works when the size of the quantities is known, either 32-bits
// or 64 bits as with the ZIP64 extensions.
//
// With Zip64, the 4-byte fields are set to 0xffffffff, and there is a
// corresponding data block in the "extra field" that contains the
// actual Compressed, uncompressed sizes. (As well as an additional
// field, the "Relative Offset of Local Header")
//
// The problem is when the app desires to use ZIP64 extensions
// optionally, only when necessary. Suppose the library assumes no
// zip64 extensions when writing the header, then after compression
// finds that the size of the data requires zip64. At this point, the
// header, already written to the file, won't have the necessary data
// block in the "extra field". The size of the entry header is fixed,
// so it is not possible to just "add on" the zip64 data block after
// compressing the file. On the other hand, always using zip64 will
// break interoperability with many other systems and apps.
//
// The approach we take is to insert a 32-byte dummy data block in the
// extra field, whenever zip64 is to be used "as necessary". This data
// block will get the actual zip64 HeaderId and zip64 metadata if
// necessary. If not necessary, the data block will get a meaningless
// HeaderId (0x1111), and will be filled with zeroes.
//
// When zip64 is actually in use, we also need to set the
// VersionNeededToExtract field to 45.
//
// There is one additional wrinkle: using zip64 as necessary conflicts
// with output to non-seekable devices. The header is emitted and
// must indicate whether zip64 is in use, before we know if zip64 is
// necessary. Because there is no seeking, the header can never be
// changed. Therefore, on non-seekable devices,
// Zip64Option.AsNecessary is the same as Zip64Option.Always.
//
// version needed- see AppNote.txt.
//
// need v5.1 for PKZIP strong encryption, or v2.0 for no encryption or
// for PK encryption, 4.5 for zip64. We may reset this later, as
// necessary or zip64.
_presumeZip64 = (_container.Zip64 == Zip64Option.Always ||
(_container.Zip64 == Zip64Option.AsNecessary && !s.CanSeek));
Int16 VersionNeededToExtract = (Int16)(_presumeZip64 ? 45 : 20);
#if BZIP
if (this.CompressionMethod == Ionic.Zip.CompressionMethod.BZip2)
VersionNeededToExtract = 46;
#endif
// (i==4)
block[i++] = (byte)(VersionNeededToExtract & 0x00FF);
block[i++] = (byte)((VersionNeededToExtract & 0xFF00) >> 8);
// Get byte array. Side effect: sets ActualEncoding.
// Must determine encoding before setting the bitfield.
// workitem 6513
byte[] fileNameBytes = GetEncodedFileNameBytes();
Int16 filenameLength = (Int16)fileNameBytes.Length;
// general purpose bitfield
// In the current implementation, this library uses only these bits
// in the GP bitfield:
// bit 0 = if set, indicates the entry is encrypted
// bit 3 = if set, indicates the CRC, C and UC sizes follow the file data.
// bit 6 = strong encryption - for pkware's meaning of strong encryption
// bit 11 = UTF-8 encoding is used in the comment and filename
// Here we set or unset the encryption bit.
// _BitField may already be set, as with a ZipEntry added into ZipOutputStream, which
// has bit 3 always set. We only want to set one bit
if (_Encryption == EncryptionAlgorithm.None)
_BitField &= ~1; // encryption bit OFF
else
_BitField |= 1; // encryption bit ON
// workitem 7941: WinZip does not the "strong encryption" bit when using AES.
// This "Strong Encryption" is a PKWare Strong encryption thing.
// _BitField |= 0x0020;
// set the UTF8 bit if necessary
#if SILVERLIGHT
if (_actualEncoding.WebName == "utf-8")
#else
if (_actualEncoding.CodePage == System.Text.Encoding.UTF8.CodePage)
#endif
_BitField |= 0x0800;
// The PKZIP spec says that if bit 3 is set (0x0008) in the General
// Purpose BitField, then the CRC, Compressed size, and uncompressed
// size are written directly after the file data.
//
// These 3 quantities are normally present in the regular zip entry
// header. But, they are not knowable until after the compression is
// done. So, in the normal case, we
//
// - write the header, using zeros for these quantities
// - compress the data, and incidentally compute these quantities.
// - seek back and write the correct values them into the header.
//
// This is nice because, while it is more complicated to write the zip
// file, it is simpler and less error prone to read the zip file, and
// as a result more applications can read zip files produced this way,
// with those 3 quantities in the header.
//
// But if seeking in the output stream is not possible, then we need
// to set the appropriate bitfield and emit these quantities after the
// compressed file data in the output.
//
// workitem 7216 - having trouble formatting a zip64 file that is
// readable by WinZip. not sure why! What I found is that setting
// bit 3 and following all the implications, the zip64 file is
// readable by WinZip 12. and Perl's IO::Compress::Zip . Perl takes
// an interesting approach - it always sets bit 3 if ZIP64 in use.
// DotNetZip now does the same; this gives better compatibility with
// WinZip 12.
if (IsDirectory || cycle == 99)
{
// (cycle == 99) indicates a zero-length entry written by ZipOutputStream
_BitField &= ~0x0008; // unset bit 3 - no "data descriptor" - ever
_BitField &= ~0x0001; // unset bit 1 - no encryption - ever
Encryption = EncryptionAlgorithm.None;
Password = null;
}
else if (!s.CanSeek)
_BitField |= 0x0008;
#if DONT_GO_THERE
else if (this.Encryption == EncryptionAlgorithm.PkzipWeak &&
this._Source != ZipEntrySource.ZipFile)
{
// Set bit 3 to avoid the double-read perf issue.
//
// When PKZIP encryption is used, byte 11 of the encryption header is
// used as a consistency check. It is normally set to the MSByte of the
// CRC. But this means the cRC must be known ebfore compression and
// encryption, which means the entire stream has to be read twice. To
// avoid that, the high-byte of the time blob (when in DOS format) can
// be used for the consistency check (byte 11 in the encryption header).
// But this means the entry must have bit 3 set.
//
// Previously I used a more complex arrangement - using the methods like
// FigureCrc32(), PrepOutputStream() and others, in order to manage the
// seek-back in the source stream. Why? Because bit 3 is not always
// friendly with third-party zip tools, like those on the Mac.
//
// This is why this code is still ifdef'd out.
//
// Might consider making this yet another programmable option -
// AlwaysUseBit3ForPkzip. But that's for another day.
//
_BitField |= 0x0008;
}
#endif
// (i==6)