zip-codec 0.0.17

Strict asynchronous ZIP decoding and encoding in safe Rust
Documentation
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
//! Streaming ZIP64 encoding.
//!
//! ## Compatibility notes
//!
//! - The decoder rejects archives with multiple apparent end-of-central-directory
//!   records. Encoding can finish successfully and still produce an archive that
//!   [`ZipArchive::open`](crate::ZipArchive::open) rejects if bytes in a member look
//!   like a second end record. [`CompressionMethod::Stored`] copies member bytes
//!   verbatim, and the default DEFLATE encoder can also preserve those bytes in
//!   uncompressed blocks.

use std::io::{self, SeekFrom};

use archive_trait::{
    ArchiveBuilder, BuildError, EntryMetadata, FilePayload, builder::BuildFailure,
};
use crc32fast::Hasher;
use flate2::{Compress, Compression, FlushCompress, Status};
use thiserror::Error;
use tokio::io::{AsyncSeek, AsyncSeekExt, AsyncWrite, AsyncWriteExt};
use zip_framing::{
    Budget, BudgetError, CompressionMethod, LimitExceeded, Limits,
    constants::size,
    write::{EntryKind, PendingMember, end_records},
};

use crate::payload::CHUNK_SIZE;

/// Options for one regular ZIP file.
///
/// Construct from [`EntryMetadata`] to set format-neutral file metadata.
/// Default options inherit the method configured by [`ZipEncoder::with_compression`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct ZipFileOptions {
    metadata: EntryMetadata,
    compression: Option<CompressionMethod>,
}

impl ZipFileOptions {
    /// Selects the compression method for this file.
    ///
    /// Empty files are always stored, regardless of this setting.
    pub fn compression(mut self, method: CompressionMethod) -> Self {
        self.compression = Some(method);
        self
    }
}

impl From<EntryMetadata> for ZipFileOptions {
    fn from(metadata: EntryMetadata) -> Self {
        Self {
            metadata,
            compression: None,
        }
    }
}

/// Resource limits for [`ZipEncoder`].
#[derive(Clone, Copy, Debug)]
pub struct EncodeLimits {
    /// Maximum number of members (default: 100,000).
    pub entries: usize,
    /// Maximum bytes in local headers, central headers, and the ZIP64 end record
    /// (default: 64 MiB).
    pub metadata_size: u64,
    /// Maximum uncompressed input size of one member (default: 8 GiB).
    pub member_size: u64,
    /// Maximum sum of uncompressed member sizes (default: 64 GiB).
    pub total_size: u64,
}

impl Default for EncodeLimits {
    fn default() -> Self {
        let Limits {
            entries,
            metadata_size,
            member_size,
            total_size,
            ..
        } = Limits::default();
        Self {
            entries,
            metadata_size,
            member_size,
            total_size,
        }
    }
}

impl EncodeLimits {
    fn budget_limits(self) -> Limits {
        Limits {
            entries: self.entries,
            metadata_size: self.metadata_size,
            member_size: self.member_size,
            total_size: self.total_size,
            archive_size: u64::MAX,
        }
    }
}

/// A streaming UTF-8 ZIP64 writer for [`ArchiveBuilder::builder`].
///
/// The output must be empty and positioned at byte zero. After writing each
/// payload, the encoder seeks back and overwrites its local header. Append mode
/// (`O_APPEND`) is unsupported because writes always go to the end of the file.
pub struct ZipEncoder<W> {
    writer: W,
    method: CompressionMethod,
    budget: Budget,
    position: u64,
    count: usize,
    directory: Vec<u8>,
    finished: bool,
}

impl<W> ZipEncoder<W> {
    /// Creates a DEFLATE encoder with default resource budgets.
    pub fn new(writer: W) -> Self {
        Self {
            writer,
            method: CompressionMethod::default(),
            budget: Budget::new(EncodeLimits::default().budget_limits()),
            position: 0,
            count: 0,
            directory: Vec::new(),
            finished: false,
        }
    }

    /// Selects the default compression method for nonempty regular files.
    ///
    /// Individual files can override this with [`ZipFileOptions::compression`].
    pub fn with_compression(mut self, method: CompressionMethod) -> Self {
        self.method = method;
        self
    }

    /// Sets entry-count, metadata, per-member input, and total input limits.
    pub fn with_limits(mut self, limits: EncodeLimits) -> Self {
        self.budget.set_limits(limits.budget_limits());
        self
    }

    /// Returns the output without finalizing an unfinished archive.
    ///
    /// Use [`archive_trait::Builder::finish_into_inner`] before calling this
    /// method to obtain a completed archive.
    pub fn into_inner(self) -> W {
        self.writer
    }
}

impl<W: AsyncWrite + AsyncSeek + Unpin> ZipEncoder<W> {
    fn prepare_member<'a>(
        &self,
        path: &'a str,
        method: CompressionMethod,
        kind: EntryKind,
        size: u64,
    ) -> Result<(PendingMember<'a>, Budget), EncodeError> {
        let header = PendingMember::new(path, method, kind)?;
        if self.finished {
            return Err(EncodeError::Finished);
        }

        let mut pending_budget = self.budget;
        pending_budget.check_entry_count(self.count as u64 + 1)?;
        pending_budget.charge_metadata(
            header.local_header_size() as u64 + header.central_header_size() as u64,
        )?;
        pending_budget.charge_member(size)?;
        check_end_metadata(pending_budget)?;

        Ok((header, pending_budget))
    }

    async fn add_member(
        &mut self,
        path: &str,
        method: CompressionMethod,
        kind: EntryKind,
        payload: &mut FilePayload<'_>,
    ) -> Result<(), BuildFailure<EncodeError>> {
        let (header, pending_budget) = self
            .prepare_member(path, method, kind, payload.size())
            .map_err(BuildFailure::recoverable)?;

        self.write_member(header, payload)
            .await
            .map_err(BuildFailure::poisoned)?;
        self.budget = pending_budget;

        Ok(())
    }

    async fn write_bytes(&mut self, bytes: &[u8]) -> Result<(), EncodeError> {
        let end = self
            .position
            .checked_add(bytes.len() as u64)
            .ok_or(EncodeError::Overflow)?;

        self.writer.write_all(bytes).await?;
        self.position = end;

        Ok(())
    }

    async fn compress_chunk(
        &mut self,
        compressor: &mut Compress,
        mut input: &[u8],
        finish: bool,
        output: &mut [u8],
    ) -> Result<(), EncodeError> {
        loop {
            let before_input = compressor.total_in();
            let before_output = compressor.total_out();
            let status = compressor
                .compress(
                    input,
                    output,
                    if finish {
                        FlushCompress::Finish
                    } else {
                        FlushCompress::None
                    },
                )
                .map_err(|_| EncodeError::Compression)?;

            let consumed = (compressor.total_in() - before_input) as usize;
            let produced = (compressor.total_out() - before_output) as usize;
            input = &input[consumed..];
            self.write_bytes(&output[..produced]).await?;

            if status == Status::StreamEnd || (!finish && input.is_empty()) {
                return Ok(());
            }

            if consumed == 0 && produced == 0 {
                return Err(EncodeError::Compression);
            }

            tokio::task::consume_budget().await;
        }
    }

    async fn write_member(
        &mut self,
        header: PendingMember<'_>,
        payload: &mut FilePayload<'_>,
    ) -> Result<(), BuildError<EncodeError>> {
        let size = payload.size();
        let offset = self.position;
        self.write_bytes(&vec![0; header.local_header_size()])
            .await?;

        let start = self.position;
        let mut crc = Hasher::new();
        let mut compressor = match header.method() {
            CompressionMethod::Stored => None,
            CompressionMethod::Deflate => Some(Compress::new(Compression::default(), false)),
            _ => return Err(EncodeError::Compression.into()),
        };
        let mut output = if compressor.is_some() {
            vec![0; CHUNK_SIZE]
        } else {
            Vec::new()
        };

        while let Some(chunk) = payload.next_chunk().await? {
            for chunk in chunk.chunks(CHUNK_SIZE) {
                crc.update(chunk);
                if let Some(compressor) = &mut compressor {
                    self.compress_chunk(compressor, chunk, false, &mut output)
                        .await?;
                } else {
                    self.write_bytes(chunk).await?;
                }

                tokio::task::consume_budget().await;
            }
        }

        if let Some(compressor) = &mut compressor {
            self.compress_chunk(compressor, &[], true, &mut output)
                .await?;
        }

        let member = header
            .finish(crc.finalize(), self.position - start, size, offset)
            .map_err(EncodeError::Framing)?;

        // Rewriting the reserved header does not advance the archive's end.
        self.writer
            .seek(SeekFrom::Start(offset))
            .await
            .map_err(EncodeError::Io)?;
        self.writer
            .write_all(&member.local_header())
            .await
            .map_err(EncodeError::Io)?;
        self.writer
            .seek(SeekFrom::Start(self.position))
            .await
            .map_err(EncodeError::Io)?;

        member.append_central_header(&mut self.directory);
        self.count += 1;

        Ok(())
    }

    fn prepare_end(&self) -> Result<(Vec<u8>, u64), EncodeError> {
        if self.finished {
            return Err(EncodeError::Finished);
        }

        check_end_metadata(self.budget)?;
        let end = end_records(
            self.count as u64,
            self.position,
            self.directory.len() as u64,
        )?;

        let position = self
            .position
            .checked_add(self.directory.len() as u64)
            .and_then(|position| position.checked_add(end.len() as u64))
            .ok_or(EncodeError::Overflow)?;
        Ok((end, position))
    }

    async fn write_end(&mut self, end: &[u8], position: u64) -> Result<(), EncodeError> {
        self.writer.write_all(&self.directory).await?;
        self.writer.write_all(end).await?;
        self.writer.flush().await?;

        self.position = position;
        self.finished = true;

        Ok(())
    }
}

impl<W: AsyncWrite + AsyncSeek + Unpin> ArchiveBuilder for ZipEncoder<W> {
    type Error = EncodeError;
    type FileOptions = ZipFileOptions;

    async fn finish_archive(&mut self) -> Result<(), BuildFailure<Self::Error>> {
        let (end, position) = self.prepare_end().map_err(BuildFailure::recoverable)?;

        self.write_end(&end, position)
            .await
            .map_err(BuildFailure::poisoned)
    }

    async fn write_file_member(
        &mut self,
        path: &str,
        payload: &mut FilePayload<'_>,
        options: Self::FileOptions,
    ) -> Result<(), BuildFailure<Self::Error>> {
        let method = if payload.size() == 0 {
            CompressionMethod::Stored
        } else {
            options.compression.unwrap_or(self.method)
        };
        self.add_member(
            path,
            method,
            EntryKind::File {
                executable: options.metadata.is_executable(),
            },
            payload,
        )
        .await
    }

    async fn write_directory_member(
        &mut self,
        path: &str,
    ) -> Result<(), BuildFailure<Self::Error>> {
        let path = if path.ends_with('/') {
            path.to_owned()
        } else {
            format!("{path}/")
        };
        self.add_member(
            &path,
            CompressionMethod::Stored,
            EntryKind::Directory,
            &mut FilePayload::from(&b""[..]),
        )
        .await
    }

    async fn write_symbolic_link_member(
        &mut self,
        path: &str,
        target: &str,
    ) -> Result<(), BuildFailure<Self::Error>> {
        if target.is_empty() || target.len() > usize::from(u16::MAX) || target.contains('\0') {
            return Err(BuildFailure::recoverable(EncodeError::InvalidLink));
        }

        // Store the target in the member payload: readers such as libarchive do not
        // read symbolic-link targets from the PKWARE UNIX extra field (0x000d).
        self.add_member(
            path,
            CompressionMethod::Stored,
            EntryKind::SymbolicLink,
            &mut FilePayload::from(target.as_bytes()),
        )
        .await
    }
}

/// Check a copy so successive members reserve the same end record.
fn check_end_metadata(mut budget: Budget) -> Result<(), BudgetError> {
    budget.charge_metadata(size::ZIP64_END as u64)
}

/// A failure while encoding ZIP records or payloads.
#[derive(Debug, Error)]
pub enum EncodeError {
    /// Metadata could not be represented in ZIP.
    #[error(transparent)]
    Framing(#[from] zip_framing::Error),
    /// Writing, seeking, or flushing the output failed.
    #[error("ZIP output I/O failed: {0}")]
    Io(#[from] io::Error),
    /// A compressor failed or made no progress.
    #[error("DEFLATE compression failed")]
    Compression,
    /// Output arithmetic exceeded the ZIP64 range.
    #[error("ZIP output size overflow")]
    Overflow,
    /// A symbolic-link target cannot be represented safely.
    #[error("empty, oversized, or NUL-containing symbolic-link target")]
    InvalidLink,
    /// A resource budget was exceeded.
    #[error(transparent)]
    Limit(#[from] LimitExceeded),
    /// The writer has already emitted its directory and terminators.
    #[error("ZIP writer is already finalized")]
    Finished,
}

impl From<EncodeError> for BuildError<EncodeError> {
    fn from(error: EncodeError) -> Self {
        Self::Encoder(error)
    }
}

impl From<BudgetError> for EncodeError {
    fn from(error: BudgetError) -> Self {
        match error {
            BudgetError::Limit(limit) => Self::Limit(limit),
            BudgetError::Overflow(_) => Self::Overflow,
        }
    }
}