-
Notifications
You must be signed in to change notification settings - Fork 105
Expand file tree
/
Copy pathwrite.rs
More file actions
4232 lines (3985 loc) · 172 KB
/
write.rs
File metadata and controls
4232 lines (3985 loc) · 172 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
//! Writing a ZIP archive
use crate::compression::CompressionMethod;
use crate::extra_fields::UsedExtraField;
use crate::read::{parse_single_extra_field, Config, ZipArchive, ZipFile};
use crate::result::{invalid, ZipError, ZipResult};
use crate::spec::{self, FixedSizeBlock, Zip32CDEBlock};
use crate::types::ffi::S_IFLNK;
use crate::types::{
ffi, AesVendorVersion, DateTime, Zip64ExtraFieldBlock, ZipFileData, ZipLocalEntryBlock,
ZipRawValues, MIN_VERSION,
};
use core::default::Default;
use core::fmt::{Debug, Formatter};
use core::marker::PhantomData;
use core::mem::{self, offset_of, size_of};
use core::str::{from_utf8, Utf8Error};
use crc32fast::Hasher;
use indexmap::IndexMap;
use std::borrow::ToOwned;
use std::io::{self, Read, Seek, Write};
use std::io::{BufReader, SeekFrom};
use std::io::{Cursor, ErrorKind};
use std::path::Path;
use std::sync::Arc;
// re-export from types
pub use crate::types::{FileOptions, SimpleFileOptions};
#[cfg_attr(feature = "aes-crypto", allow(clippy::large_enum_variant))]
enum MaybeEncrypted<W> {
Unencrypted(W),
#[cfg(feature = "aes-crypto")]
Aes(crate::aes::AesWriter<W>),
ZipCrypto(crate::zipcrypto::ZipCryptoWriter<W>),
}
impl<W> Debug for MaybeEncrypted<W> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
// Don't print W, since it may be a huge Vec<u8>
f.write_str(match self {
MaybeEncrypted::Unencrypted(_) => "Unencrypted",
#[cfg(feature = "aes-crypto")]
MaybeEncrypted::Aes(_) => "AES",
MaybeEncrypted::ZipCrypto(_) => "ZipCrypto",
})
}
}
impl<W: Write> Write for MaybeEncrypted<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match self {
MaybeEncrypted::Unencrypted(w) => w.write(buf),
#[cfg(feature = "aes-crypto")]
MaybeEncrypted::Aes(w) => w.write(buf),
MaybeEncrypted::ZipCrypto(w) => w.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match self {
MaybeEncrypted::Unencrypted(w) => w.flush(),
#[cfg(feature = "aes-crypto")]
MaybeEncrypted::Aes(w) => w.flush(),
MaybeEncrypted::ZipCrypto(w) => w.flush(),
}
}
}
enum GenericZipWriter<W: Write + Seek> {
Closed,
Storer(MaybeEncrypted<W>),
#[cfg(feature = "deflate-flate2")]
Deflater(flate2::write::DeflateEncoder<MaybeEncrypted<W>>),
#[cfg(feature = "deflate-zopfli")]
ZopfliDeflater(zopfli::DeflateEncoder<MaybeEncrypted<W>>),
#[cfg(feature = "deflate-zopfli")]
BufferedZopfliDeflater(std::io::BufWriter<zopfli::DeflateEncoder<MaybeEncrypted<W>>>),
#[cfg(feature = "_bzip2_any")]
Bzip2(bzip2::write::BzEncoder<MaybeEncrypted<W>>),
#[cfg(feature = "zstd")]
Zstd(zstd::stream::write::Encoder<'static, MaybeEncrypted<W>>),
#[cfg(feature = "xz")]
Xz(Box<lzma_rust2::XzWriter<MaybeEncrypted<W>>>),
#[cfg(feature = "ppmd")]
Ppmd(Box<ppmd_rust::Ppmd8Encoder<MaybeEncrypted<W>>>),
}
impl<W: Write + Seek> Debug for GenericZipWriter<W> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Self::Closed => f.write_str("Closed"),
Self::Storer(w) => f.write_fmt(format_args!("Storer({w:?})")),
#[cfg(feature = "deflate-flate2")]
Self::Deflater(w) => f.write_fmt(format_args!("Deflater({:?})", w.get_ref())),
#[cfg(feature = "deflate-zopfli")]
Self::ZopfliDeflater(_) => f.write_str("ZopfliDeflater"),
#[cfg(feature = "deflate-zopfli")]
Self::BufferedZopfliDeflater(_) => f.write_str("BufferedZopfliDeflater"),
#[cfg(feature = "_bzip2_any")]
Self::Bzip2(w) => f.write_fmt(format_args!("Bzip2({:?})", w.get_ref())),
#[cfg(feature = "zstd")]
Self::Zstd(w) => f.write_fmt(format_args!("Zstd({:?})", w.get_ref())),
#[cfg(feature = "xz")]
Self::Xz(w) => f.write_fmt(format_args!("Xz({:?})", w.inner())),
#[cfg(feature = "ppmd")]
Self::Ppmd(_) => f.write_fmt(format_args!("Ppmd8Encoder")),
}
}
}
// Put the struct declaration in a private module to convince rustdoc to display ZipWriter nicely
pub(crate) mod zip_writer {
use core::fmt::{Debug, Formatter};
use std::io::{Seek, Write};
use indexmap::IndexMap;
use crate::{
types::ZipFileData,
write::{GenericZipWriter, ZipWriterStats},
};
/// ZIP archive generator
///
/// Handles the bookkeeping involved in building an archive, and provides an
/// API to edit its contents.
///
/// ```
/// # fn doit() -> zip::result::ZipResult<()>
/// # {
/// # use zip::ZipWriter;
/// use std::io::Write;
/// use zip::write::SimpleFileOptions;
///
/// // We use a cursor + vec here, though you'd normally use a `File`
/// let mut cur = std::io::Cursor::new(Vec::new());
/// let mut zip = ZipWriter::new(&mut cur);
///
/// let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
/// zip.start_file("hello_world.txt", options)?;
/// zip.write(b"Hello, World!")?;
///
/// // Apply the changes you've made.
/// // Dropping the `ZipWriter` will have the same effect, but may silently fail
/// zip.finish()?;
///
/// // raw zip data is available as a Vec<u8>
/// let zip_bytes = cur.into_inner();
///
/// # Ok(())
/// # }
/// # doit().unwrap();
/// ```
pub struct ZipWriter<W: Write + Seek> {
pub(super) inner: GenericZipWriter<W>,
pub(super) files: IndexMap<Box<str>, ZipFileData>,
pub(super) stats: ZipWriterStats,
pub(super) writing_to_file: bool,
pub(super) writing_raw: bool,
pub(super) comment: Box<[u8]>,
pub(super) zip64_comment: Option<Box<[u8]>>,
pub(super) flush_on_finish_file: bool,
pub(super) seek_possible: bool,
pub(crate) auto_large_file: bool,
}
impl<W: Write + Seek> Debug for ZipWriter<W> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"ZipWriter {{files: {:?}, stats: {:?}, writing_to_file: {}, writing_raw: {}, comment: {:?}, flush_on_finish_file: {}}}",
self.files, self.stats, self.writing_to_file, self.writing_raw,
self.comment, self.flush_on_finish_file))
}
}
}
#[doc(inline)]
pub use self::sealed::FileOptionExtension;
use crate::result::ZipError::UnsupportedArchive;
use crate::unstable::path_to_string;
use crate::unstable::LittleEndianWriteExt;
use crate::zipcrypto::{EncryptWith, ZipCryptoKeys, CHUNK_SIZE};
use crate::CompressionMethod::Stored;
pub use zip_writer::ZipWriter;
#[derive(Default, Debug)]
struct ZipWriterStats {
hasher: Hasher,
start: u64,
bytes_written: u64,
}
mod sealed {
use std::sync::Arc;
use super::ExtendedFileOptions;
pub trait Sealed {}
/// File options Extensions
#[doc(hidden)]
pub trait FileOptionExtension: Default + Sealed {
/// Extra Data
fn extra_data(&self) -> Option<&Arc<Vec<u8>>>;
/// Central Extra Data
fn central_extra_data(&self) -> Option<&Arc<Vec<u8>>>;
/// File Comment
fn file_comment(&self) -> Option<&str>;
/// Take File Comment (moves ownership)
fn take_file_comment(&mut self) -> Option<Box<str>>;
}
impl Sealed for () {}
impl FileOptionExtension for () {
fn extra_data(&self) -> Option<&Arc<Vec<u8>>> {
None
}
fn central_extra_data(&self) -> Option<&Arc<Vec<u8>>> {
None
}
fn file_comment(&self) -> Option<&str> {
None
}
fn take_file_comment(&mut self) -> Option<Box<str>> {
None
}
}
impl Sealed for ExtendedFileOptions {}
impl FileOptionExtension for ExtendedFileOptions {
fn extra_data(&self) -> Option<&Arc<Vec<u8>>> {
Some(&self.extra_data)
}
fn central_extra_data(&self) -> Option<&Arc<Vec<u8>>> {
Some(&self.central_extra_data)
}
fn file_comment(&self) -> Option<&str> {
self.file_comment.as_ref().map(Box::as_ref)
}
fn take_file_comment(&mut self) -> Option<Box<str>> {
self.file_comment.take()
}
}
}
/// Adds Extra Data and Central Extra Data. It does not implement copy.
pub type FullFileOptions<'k> = FileOptions<'k, ExtendedFileOptions>;
/// The Extension for Extra Data and Central Extra Data
#[cfg_attr(feature = "_arbitrary", derive(arbitrary::Arbitrary))]
#[derive(Clone, Default, Eq, PartialEq)]
pub struct ExtendedFileOptions {
extra_data: Arc<Vec<u8>>,
central_extra_data: Arc<Vec<u8>>,
file_comment: Option<Box<str>>,
}
impl ExtendedFileOptions {
/// Adds an extra data field, unless we detect that it's invalid.
pub fn add_extra_data<D: AsRef<[u8]>>(
&mut self,
header_id: u16,
data: D,
central_only: bool,
) -> ZipResult<()> {
let data = data.as_ref();
let len = data.len() + 4;
if self.extra_data.len() + self.central_extra_data.len() + len > u16::MAX as usize {
Err(invalid!("Extra data field would be longer than allowed"))
} else {
let field = if central_only {
&mut self.central_extra_data
} else {
&mut self.extra_data
};
let vec = Arc::make_mut(field);
Self::add_extra_data_unchecked(vec, header_id, data)?;
Self::validate_extra_data(vec, true)?;
Ok(())
}
}
pub(crate) fn add_extra_data_unchecked(
vec: &mut Vec<u8>,
header_id: u16,
data: &[u8],
) -> Result<(), ZipError> {
vec.reserve_exact(data.len() + 4);
vec.write_u16_le(header_id)?;
vec.write_u16_le(data.len() as u16)?;
vec.write_all(data)?;
Ok(())
}
fn validate_extra_data(data: &[u8], disallow_zip64: bool) -> ZipResult<()> {
let len = data.len() as u64;
if len == 0 {
return Ok(());
}
if len > u64::from(u16::MAX) {
return Err(ZipError::Io(io::Error::other(
"Extra-data field can't exceed u16::MAX bytes",
)));
}
let mut data = Cursor::new(data);
let mut pos = data.position();
while pos < len {
if len - data.position() < 4 {
return Err(ZipError::Io(io::Error::other(
"Extra-data field doesn't have room for ID and length",
)));
}
#[cfg(not(feature = "unreserved"))]
{
use crate::{
extra_fields::{UsedExtraField, EXTRA_FIELD_MAPPING},
unstable::LittleEndianReadExt,
};
let header_id = data.read_u16_le()?;
// Some extra fields are authorized
if let Err(()) = UsedExtraField::try_from(header_id) {
if EXTRA_FIELD_MAPPING.contains(&header_id) {
return Err(ZipError::Io(io::Error::other(format!(
"Extra data header ID {:#06} (0x{:x}) \
requires crate feature \"unreserved\"",
header_id, header_id,
))));
}
}
data.seek(SeekFrom::Current(-2))?;
}
parse_single_extra_field(&mut ZipFileData::default(), &mut data, pos, disallow_zip64)?;
pos = data.position();
}
Ok(())
}
}
impl Debug for ExtendedFileOptions {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_fmt(format_args!("ExtendedFileOptions {{extra_data: vec!{:?}.into(), central_extra_data: vec!{:?}.into()}}",
self.extra_data, self.central_extra_data))
}
}
#[cfg(feature = "_arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for FileOptions<'a, ExtendedFileOptions> {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let mut options = FullFileOptions {
compression_method: CompressionMethod::arbitrary(u)?,
compression_level: if bool::arbitrary(u)? {
Some(u.int_in_range(0..=24)?)
} else {
None
},
last_modified_time: DateTime::arbitrary(u)?,
permissions: Option::<u32>::arbitrary(u)?,
large_file: bool::arbitrary(u)?,
encrypt_with: Option::<EncryptWith<'_>>::arbitrary(u)?,
alignment: u16::arbitrary(u)?,
#[cfg(feature = "deflate-zopfli")]
zopfli_buffer_size: None,
..Default::default()
};
#[cfg(feature = "deflate-zopfli")]
if options.compression_method == CompressionMethod::Deflated && bool::arbitrary(u)? {
options.zopfli_buffer_size =
Some(if bool::arbitrary(u)? { 2 } else { 3 } << u.int_in_range(8..=20)?);
}
u.arbitrary_loop(Some(0), Some(10), |u| {
options
.add_extra_data(
u.int_in_range(2..=u16::MAX)?,
Box::<[u8]>::arbitrary(u)?,
bool::arbitrary(u)?,
)
.map_err(|_| arbitrary::Error::IncorrectFormat)?;
Ok(core::ops::ControlFlow::Continue(()))
})?;
ZipWriter::new(Cursor::new(Vec::new()))
.start_file("", options.clone())
.map_err(|_| arbitrary::Error::IncorrectFormat)?;
Ok(options)
}
}
const DEFAULT_FILE_PERMISSIONS: u32 = 0o644; // rw-r--r-- default for regular files
const DEFAULT_DIR_PERMISSIONS: u32 = 0o755; // rwxr-xr-x default for directories
impl<T: FileOptionExtension> FileOptions<'_, T> {
pub(crate) fn normalize(&mut self) {
if !self.last_modified_time.is_valid() {
self.last_modified_time = FileOptions::<T>::default().last_modified_time;
}
*self.permissions.get_or_insert(DEFAULT_FILE_PERMISSIONS) |= ffi::S_IFREG;
}
/// Indicates whether this file will be encrypted (whether with AES or `ZipCrypto`).
pub const fn has_encryption(&self) -> bool {
#[cfg(feature = "aes-crypto")]
{
self.encrypt_with.is_some() || self.aes_mode.is_some()
}
#[cfg(not(feature = "aes-crypto"))]
{
self.encrypt_with.is_some()
}
}
/// Set the compression method for the new file
///
/// The default is [`CompressionMethod::Deflated`] if it is enabled. If not,
/// [`CompressionMethod::Bzip2`] is the default if it is enabled. If neither `bzip2` nor `deflate`
/// is enabled, [`CompressionMethod::Stored`] becomes the default and files are written uncompressed.
#[must_use]
pub const fn compression_method(mut self, method: CompressionMethod) -> Self {
self.compression_method = method;
self
}
/// Set the compression level for the new file
///
/// `None` value specifies default compression level.
///
/// Range of values depends on compression method:
/// * `Deflated`: 10 - 264 for Zopfli, 0 - 9 for other encoders. Default is 24 if Zopfli is the
/// only encoder, or 6 otherwise.
/// * `Bzip2`: 0 - 9. Default is 6
/// * `Zstd`: -7 - 22, with zero being mapped to default level. Default is 3
/// * others: only `None` is allowed
#[must_use]
pub const fn compression_level(mut self, level: Option<i64>) -> Self {
self.compression_level = level;
self
}
/// Set the last modified time
///
/// The default is the current timestamp if the 'time' feature is enabled, and 1980-01-01
/// otherwise
#[must_use]
pub const fn last_modified_time(mut self, mod_time: DateTime) -> Self {
self.last_modified_time = mod_time;
self
}
/// Set the permissions for the new file.
///
/// The format is represented with unix-style permissions.
/// The default is `0o644`, which represents `rw-r--r--` for files,
/// and `0o755`, which represents `rwxr-xr-x` for directories.
///
/// This method only preserves the file permissions bits (via a `& 0o777`) and discards
/// higher file mode bits. So it cannot be used to denote an entry as a directory,
/// symlink, or other special file type.
#[must_use]
pub const fn unix_permissions(mut self, mode: u32) -> Self {
self.permissions = Some(mode & 0o777);
self
}
/// Set whether the new file's compressed and uncompressed size is less than 4 GiB.
///
/// If set to `false` and the file exceeds the limit, an I/O error is thrown and the file is
/// aborted. If set to `true`, readers will require ZIP64 support and if the file does not
/// exceed the limit, 20 B are wasted. The default is `false`.
#[must_use]
pub const fn large_file(mut self, large: bool) -> Self {
self.large_file = large;
self
}
pub(crate) fn with_deprecated_encryption(self, password: &[u8]) -> FileOptions<'static, T> {
FileOptions {
encrypt_with: Some(EncryptWith::ZipCrypto(
ZipCryptoKeys::derive(password),
PhantomData,
)),
..self
}
}
/// Set the AES encryption parameters.
#[cfg(feature = "aes-crypto")]
pub fn with_aes_encryption(self, mode: crate::AesMode, password: &str) -> FileOptions<'_, T> {
FileOptions {
encrypt_with: Some(EncryptWith::Aes { mode, password }),
..self
}
}
/// Sets the size of the buffer used to hold the next block that Zopfli will compress. The
/// larger the buffer, the more effective the compression, but the more memory is required.
/// A value of `None` indicates no buffer, which is recommended only when all non-empty writes
/// are larger than about 32 KiB.
#[must_use]
#[cfg(feature = "deflate-zopfli")]
pub const fn with_zopfli_buffer(mut self, size: Option<usize>) -> Self {
self.zopfli_buffer_size = size;
self
}
/// Returns the compression level currently set.
pub const fn get_compression_level(&self) -> Option<i64> {
self.compression_level
}
/// Sets the alignment to the given number of bytes.
#[must_use]
pub const fn with_alignment(mut self, alignment: u16) -> Self {
self.alignment = alignment;
self
}
}
impl FileOptions<'_, ExtendedFileOptions> {
/// Set the file comment.
#[must_use]
pub fn with_file_comment<S: Into<Box<str>>>(mut self, comment: S) -> Self {
self.extended_options.file_comment = Some(comment.into());
self
}
/// Adds an extra data field.
pub fn add_extra_data<D: AsRef<[u8]>>(
&mut self,
header_id: u16,
data: D,
central_only: bool,
) -> ZipResult<()> {
self.extended_options
.add_extra_data(header_id, data, central_only)
}
/// Removes the extra data fields.
#[must_use]
pub fn clear_extra_data(mut self) -> Self {
if !self.extended_options.extra_data.is_empty() {
self.extended_options.extra_data = Arc::new(vec![]);
}
if !self.extended_options.central_extra_data.is_empty() {
self.extended_options.central_extra_data = Arc::new(vec![]);
}
self
}
}
impl FileOptions<'static, ()> {
/// Constructs a const `FileOptions` object.
///
/// Note: This value is different than the return value of [`FileOptions::default()`]:
///
/// - The `last_modified_time` is [`DateTime::DEFAULT`]. This corresponds to 1980-01-01 00:00:00
pub const DEFAULT: Self = Self {
compression_method: CompressionMethod::DEFAULT,
compression_level: None,
last_modified_time: DateTime::DEFAULT,
large_file: false,
permissions: None,
encrypt_with: None,
extended_options: (),
alignment: 1,
#[cfg(feature = "deflate-zopfli")]
zopfli_buffer_size: Some(1 << 15),
#[cfg(feature = "aes-crypto")]
aes_mode: None,
};
}
impl<'k> FileOptions<'k, ()> {
/// Convert to FullFileOptions.
pub fn into_full_options(self) -> FullFileOptions<'k> {
FileOptions {
compression_method: self.compression_method,
compression_level: self.compression_level,
last_modified_time: self.last_modified_time,
permissions: self.permissions,
large_file: self.large_file,
encrypt_with: self.encrypt_with,
extended_options: ExtendedFileOptions::default(),
alignment: self.alignment,
#[cfg(feature = "deflate-zopfli")]
zopfli_buffer_size: self.zopfli_buffer_size,
#[cfg(feature = "aes-crypto")]
aes_mode: self.aes_mode,
}
}
}
impl<T: FileOptionExtension> Default for FileOptions<'_, T> {
/// Construct a new `FileOptions` object
fn default() -> Self {
Self {
compression_method: CompressionMethod::default(),
compression_level: None,
last_modified_time: DateTime::default_for_write(),
permissions: None,
large_file: false,
encrypt_with: None,
extended_options: T::default(),
alignment: 1,
#[cfg(feature = "deflate-zopfli")]
zopfli_buffer_size: Some(1 << 15),
#[cfg(feature = "aes-crypto")]
aes_mode: None,
}
}
}
impl<W: Write + Seek> Write for ZipWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if !self.writing_to_file {
return Err(io::Error::other("No file has been started"));
}
if buf.is_empty() {
return Ok(0);
}
match self.inner.ref_mut() {
Some(ref mut w) => {
let write_result = w.write(buf);
if let Ok(count) = write_result {
self.stats.update(&buf[..count]);
if self.stats.bytes_written > spec::ZIP64_BYTES_THR
&& !self
.files
.last()
.ok_or_else(|| std::io::Error::other("Cannot get last file"))?
.1
.large_file
{
return Err(if let Err(e) = self.abort_file() {
let abort_io_err: io::Error = e.into();
io::Error::new(
abort_io_err.kind(),
format!("Large file option has not been set and abort_file() failed: {abort_io_err}")
)
} else {
io::Error::other("Large file option has not been set")
});
}
}
write_result
}
None => Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"write(): ZipWriter was already closed",
)),
}
}
fn flush(&mut self) -> io::Result<()> {
match self.inner.ref_mut() {
Some(ref mut w) => w.flush(),
None => Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"flush(): ZipWriter was already closed",
)),
}
}
}
impl ZipWriterStats {
fn update(&mut self, buf: &[u8]) {
self.hasher.update(buf);
self.bytes_written += buf.len() as u64;
}
}
impl<A: Read + Write + Seek> ZipWriter<A> {
/// Initializes the archive from an existing ZIP archive, making it ready for append.
///
/// This uses a default configuration to initially read the archive.
pub fn new_append(readwriter: A) -> ZipResult<ZipWriter<A>> {
Self::new_append_with_config(Config::default(), readwriter)
}
/// Initializes the archive from an existing ZIP archive, making it ready for append.
///
/// This uses the given read configuration to initially read the archive.
pub fn new_append_with_config(config: Config, mut readwriter: A) -> ZipResult<ZipWriter<A>> {
readwriter.seek(SeekFrom::Start(0))?;
let shared = ZipArchive::get_metadata(config, &mut readwriter)?;
Ok(ZipWriter {
inner: GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(readwriter)),
files: shared.files,
stats: ZipWriterStats::default(),
writing_to_file: false,
comment: shared.comment,
zip64_comment: shared.zip64_comment,
writing_raw: true, // avoid recomputing the last file's header
flush_on_finish_file: false,
seek_possible: true,
auto_large_file: false,
})
}
/// `flush_on_finish_file` is designed to support a streaming `inner` that may unload flushed
/// bytes. It flushes a file's header and body once it starts writing another file. A `ZipWriter`
/// will not try to seek back into where a previous file was written unless
/// either [`ZipWriter::abort_file`] is called while [`ZipWriter::is_writing_file`] returns
/// false, or [`ZipWriter::deep_copy_file`] is called. In the latter case, it will only need to
/// read previously-written files and not overwrite them.
///
/// Note: when using an `inner` that cannot overwrite flushed bytes, do not wrap it in a
/// [`BufWriter`], because that has a [`Seek::seek`] method that implicitly calls
/// [`BufWriter::flush`], and `ZipWriter` needs to seek backward to update each file's header with
/// the size and checksum after writing the body.
///
/// This setting is false by default.
pub fn set_flush_on_finish_file(&mut self, flush_on_finish_file: bool) {
self.flush_on_finish_file = flush_on_finish_file;
}
}
impl<A: Read + Write + Seek> ZipWriter<A> {
/// Adds another copy of a file already in this archive. This will produce a larger but more
/// widely-compatible archive compared to [`Self::shallow_copy_file`]. Does not copy alignment.
pub fn deep_copy_file(&mut self, src_name: &str, dest_name: &str) -> ZipResult<()> {
self.finish_file()?;
if src_name == dest_name || self.files.contains_key(dest_name) {
return Err(invalid!("That file already exists"));
}
let write_position = self.inner.try_inner_mut()?.stream_position()?;
let src_index = self.index_by_name(src_name)?;
let src_data = &mut self.files[src_index];
let src_data_start = src_data.data_start(self.inner.try_inner_mut()?)?;
debug_assert!(src_data_start <= write_position);
let mut compressed_size = src_data.compressed_size;
if compressed_size > (write_position - src_data_start) {
compressed_size = write_position - src_data_start;
src_data.compressed_size = compressed_size;
}
let mut reader = BufReader::new(self.inner.try_inner_mut()?);
reader.seek(SeekFrom::Start(src_data_start))?;
let mut copy = vec![0; compressed_size as usize];
reader.take(compressed_size).read_exact(&mut copy)?;
self.inner
.try_inner_mut()?
.seek(SeekFrom::Start(write_position))?;
let mut new_data = src_data.clone();
let dest_name_raw = dest_name.as_bytes();
new_data.file_name = dest_name.into();
new_data.file_name_raw = dest_name_raw.into();
new_data.is_utf8 = !dest_name.is_ascii();
new_data.header_start = write_position;
let extra_data_start = write_position
+ size_of::<ZipLocalEntryBlock>() as u64
+ new_data.file_name_raw.len() as u64;
new_data.extra_data_start = Some(extra_data_start);
if let Some(extra) = &src_data.extra_field {
let stripped = strip_alignment_extra_field(extra);
if !stripped.is_empty() {
new_data.extra_field = Some(stripped.into());
} else {
new_data.extra_field = None;
}
}
let mut data_start = extra_data_start;
if let Some(extra) = &new_data.extra_field {
data_start += extra.len() as u64;
}
new_data.data_start.take();
new_data.data_start.get_or_init(|| data_start);
new_data.central_header_start = 0;
let block = new_data.local_block()?;
let index = self.insert_file_data(new_data)?;
let new_data = &self.files[index];
let result: io::Result<()> = {
let plain_writer = self.inner.try_inner_mut()?;
block.write(plain_writer)?;
plain_writer.write_all(&new_data.file_name_raw)?;
if let Some(data) = &new_data.extra_field {
plain_writer.write_all(data)?;
}
debug_assert_eq!(data_start, plain_writer.stream_position()?);
self.writing_to_file = true;
plain_writer.write_all(©)?;
if self.flush_on_finish_file {
plain_writer.flush()?;
}
Ok(())
};
self.ok_or_abort_file(result)?;
self.writing_to_file = false;
Ok(())
}
/// Like `deep_copy_file`, but uses Path arguments.
///
/// This function ensures that the '/' path separator is used and normalizes `.` and `..`. It
/// ignores any `..` or Windows drive letter that would produce a path outside the ZIP file's
/// root.
pub fn deep_copy_file_from_path<T: AsRef<Path>, U: AsRef<Path>>(
&mut self,
src_path: T,
dest_path: U,
) -> ZipResult<()> {
let src = path_to_string(src_path)?;
let dest = path_to_string(dest_path)?;
self.deep_copy_file(&src, &dest)
}
/// Write the zip file into the backing stream, then produce a readable archive of that data.
///
/// This method avoids parsing the central directory records at the end of the stream for
/// a slight performance improvement over running [`ZipArchive::new()`] on the output of
/// [`Self::finish()`].
///
///```
/// # fn main() -> Result<(), zip::result::ZipError> {
/// # #[cfg(any(feature = "deflate-flate2", not(feature = "_deflate-any")))]
/// # {
/// use std::io::{Cursor, Read, Write};
/// use zip::{ZipArchive, ZipWriter, write::SimpleFileOptions};
///
/// let buf = Cursor::new(Vec::new());
/// let mut zip = ZipWriter::new(buf);
/// let options = SimpleFileOptions::default();
/// zip.start_file("a.txt", options)?;
/// zip.write_all(b"hello\n")?;
///
/// let mut zip = zip.finish_into_readable()?;
/// let mut s: String = String::new();
/// zip.by_name("a.txt")?.read_to_string(&mut s)?;
/// assert_eq!(s, "hello\n");
/// # }
/// # Ok(())
/// # }
///```
pub fn finish_into_readable(mut self) -> ZipResult<ZipArchive<A>> {
let central_start = self.finalize()?;
let inner = self.close_writer()?;
let comment = mem::take(&mut self.comment);
let zip64_comment = mem::take(&mut self.zip64_comment);
let files = mem::take(&mut self.files);
let archive =
ZipArchive::from_finalized_writer(files, comment, zip64_comment, inner, central_start)?;
Ok(archive)
}
}
impl<W: Write + Seek> ZipWriter<W> {
/// Initializes the archive.
///
/// Before writing to this object, the [`ZipWriter::start_file`] function should be called.
/// After a successful write, the file remains open for writing. After a failed write, call
/// [`ZipWriter::is_writing_file`] to determine if the file remains open.
pub fn new(inner: W) -> ZipWriter<W> {
ZipWriter {
inner: GenericZipWriter::Storer(MaybeEncrypted::Unencrypted(inner)),
files: IndexMap::new(),
stats: Default::default(),
writing_to_file: false,
writing_raw: false,
comment: Box::new([]),
zip64_comment: None,
flush_on_finish_file: false,
seek_possible: true,
auto_large_file: false,
}
}
/// Set automatically large file to true if needed
pub fn set_auto_large_file(mut self) -> Self {
self.auto_large_file = true;
self
}
/// Returns true if a file is currently open for writing.
pub const fn is_writing_file(&self) -> bool {
self.writing_to_file && !self.inner.is_closed()
}
/// Set ZIP archive comment.
pub fn set_comment<S>(&mut self, comment: S)
where
S: Into<Box<str>>,
{
self.set_raw_comment(comment.into().into_boxed_bytes());
}
/// Set ZIP archive comment.
///
/// This sets the raw bytes of the comment. The comment
/// is typically expected to be encoded in UTF-8.
pub fn set_raw_comment(&mut self, comment: Box<[u8]>) {
let max_comment_len = u16::MAX as usize; // 65,535
if comment.len() > max_comment_len {
self.set_raw_zip64_comment(Some(comment));
self.comment = Box::new([]);
} else {
self.comment = comment;
self.set_raw_zip64_comment(None);
}
}
/// Get ZIP archive comment.
pub fn get_comment(&mut self) -> Result<&str, Utf8Error> {
from_utf8(self.get_raw_comment())
}
/// Get ZIP archive comment.
///
/// This returns the raw bytes of the comment. The comment
/// is typically expected to be encoded in UTF-8.
pub const fn get_raw_comment(&self) -> &[u8] {
&self.comment
}
/// Set ZIP64 archive comment.
pub fn set_zip64_comment<S>(&mut self, comment: Option<S>)
where
S: Into<Box<str>>,
{
self.set_raw_zip64_comment(comment.map(|v| v.into().into_boxed_bytes()));
}
/// Set ZIP64 archive comment.
///
/// This sets the raw bytes of the comment. The comment
/// is typically expected to be encoded in UTF-8.
pub fn set_raw_zip64_comment(&mut self, comment: Option<Box<[u8]>>) {
self.zip64_comment = comment;
}
/// Get ZIP64 archive comment.
pub fn get_zip64_comment(&mut self) -> Option<Result<&str, Utf8Error>> {
self.get_raw_zip64_comment().map(from_utf8)
}
/// Get ZIP archive comment.
///
/// This returns the raw bytes of the comment. The comment
/// is typically expected to be encoded in UTF-8.
pub fn get_raw_zip64_comment(&self) -> Option<&[u8]> {
self.zip64_comment.as_deref()
}
/// Set the file length and crc32 manually.
///
/// # Safety
///
/// This overwrites the internal crc32 calculation. It should only be used in case
/// the underlying [Write] is written independently and you need to adjust the zip metadata.
pub unsafe fn set_file_metadata(&mut self, length: u64, crc32: u32) -> ZipResult<()> {
if !self.writing_to_file {
return Err(ZipError::Io(io::Error::other("No file has been started")));
}
self.stats.hasher = Hasher::new_with_initial_len(crc32, length);
self.stats.bytes_written = length;
Ok(())
}
fn ok_or_abort_file<T, E: Into<ZipError>>(&mut self, result: Result<T, E>) -> ZipResult<T> {
match result {
Err(e) => {
let _ = self.abort_file();
Err(e.into())
}
Ok(t) => Ok(t),
}
}
/// Start a new file for with the requested options.
fn start_entry<S: ToString, T: FileOptionExtension>(
&mut self,
name: S,
mut options: FileOptions<'_, T>,
raw_values: Option<ZipRawValues>,
) -> ZipResult<()> {
self.finish_file()?;
let header_start = self.inner.try_inner_mut()?.stream_position()?;
let raw_values = raw_values.unwrap_or(ZipRawValues {
crc32: 0,
compressed_size: 0,
uncompressed_size: 0,
});
// Check if we're close to the 4GB boundary and force ZIP64 if needed
// This ensures we properly handle appending to files close to 4GB
if header_start > spec::ZIP64_BYTES_THR {
// Files that start on or past the 4GiB boundary are always ZIP64
options.large_file = true;
}
let mut extra_data = match options.extended_options.extra_data() {
Some(data) => data.to_vec(),
None => vec![],
};
let central_extra_data = options.extended_options.central_extra_data();
if let Some(zip64_block) =
Zip64ExtraFieldBlock::maybe_new(options.large_file, 0, 0, header_start)
{
let mut new_extra_data = zip64_block.serialize().into_vec();
new_extra_data.append(&mut extra_data);
extra_data = new_extra_data;
}
// Figure out the underlying compression_method and aes mode when using
// AES encryption.
let (compression_method, aes_mode) = match options.encrypt_with {
// Preserve AES method for raw copies without needing a password