Skip to main content

zip_framing/
write.rs

1//! Canonical UTF-8, single-volume ZIP64 record serialization.
2//!
3//! Completed members serialize matching local and central headers without data
4//! descriptors. Writers can reserve local header space before streaming data.
5
6use crate::{
7    CompressionMethod, Error, ExtraHeaderId, HostSystem, add,
8    constants::{extra, signature, size, version},
9    invalid,
10    kind::{ExternalAttributes, UnixFileType},
11    record::{
12        Common, GeneralPurposeFlags, MemberHeader, MemberPayload, PayloadFields, SizeField,
13        validate_name,
14    },
15};
16
17// APPNOTE 4.4.2: the high byte identifies the host system for external
18// attributes; the low byte is the ZIP specification version (45 = 4.5).
19// We always emit UNIX mode bits, regardless of the platform running the encoder.
20const VERSION_MADE_BY: u16 = ((HostSystem::Unix.to_wire() as u16) << 8) | version::ZIP64;
21
22// 00:00:00, 1980-01-01 in the DOS date/time format.
23const DEFAULT_TIME: u16 = 0;
24const DEFAULT_DATE: u16 = 0x0021;
25
26/// A portable file type represented by the encoder's Unix attributes.
27#[derive(Clone, Copy, Debug)]
28pub enum EntryKind {
29    /// A regular file, optionally carrying executable intent.
30    File { executable: bool },
31    /// A directory, whose serialized name ends in `/`.
32    Directory,
33    /// A symbolic link with its UTF-8 target stored in the payload.
34    SymbolicLink,
35}
36
37/// Validated metadata for a ZIP64 member awaiting its final CRC and sizes.
38///
39/// Once the payload's CRC and sizes are known, [`Self::finish`] produces a
40/// [`CompletedMember`] that can serialize the local and central headers.
41pub struct PendingMember<'a> {
42    path: &'a str,
43    method: CompressionMethod,
44    kind: EntryKind,
45}
46
47impl<'a> PendingMember<'a> {
48    /// Checks the path and method before any output is written.
49    ///
50    /// Enforces the APPNOTE 4.4.10 through 4.4.12 recommendation of at most
51    /// 65,535 bytes per central-directory entry.
52    pub fn new(path: &'a str, method: CompressionMethod, kind: EntryKind) -> Result<Self, Error> {
53        let member = Self { path, method, kind };
54        if path.is_empty() || member.central_header_size() > usize::from(u16::MAX) {
55            return Err(invalid(0, "empty or oversized filename"));
56        }
57
58        validate_name(path, 0)?;
59        if path.contains('\\') {
60            return Err(invalid(0, "invalid ZIP filename"));
61        }
62        if path.ends_with('/') != matches!(kind, EntryKind::Directory) {
63            return Err(invalid(0, "filename suffix disagrees with member kind"));
64        }
65
66        if matches!(kind, EntryKind::Directory) && method != CompressionMethod::Stored {
67            return Err(invalid(0, "directories must be stored without file data"));
68        }
69
70        Ok(member)
71    }
72
73    /// Returns the payload compression method.
74    pub fn method(&self) -> CompressionMethod {
75        self.method
76    }
77
78    /// Returns the space to reserve for the completed local header.
79    pub fn local_header_size(&self) -> usize {
80        size::LOCAL + extra::HEADER_SIZE + extra::ZIP64_LOCAL_SIZE + self.path.len()
81    }
82
83    /// Returns the central header size in bytes, including the filename and
84    /// ZIP64 extra field.
85    pub fn central_header_size(&self) -> usize {
86        size::CENTRAL + extra::HEADER_SIZE + extra::ZIP64_CENTRAL_SIZE + self.path.len()
87    }
88
89    /// Completes metadata after the payload's CRC and sizes are known.
90    pub fn finish(
91        self,
92        crc: u32,
93        compressed: u64,
94        uncompressed: u64,
95        offset: u64,
96    ) -> Result<CompletedMember<'a>, Error> {
97        let payload = PayloadFields {
98            crc,
99            compressed,
100            uncompressed,
101        }
102        .validate(self.method, offset)?;
103
104        // APPNOTE 4.3.8 excludes file data for empty members.
105        if payload.has_empty_deflate_stream() {
106            return Err(invalid(offset, "empty member has file data"));
107        }
108
109        if matches!(self.kind, EntryKind::Directory) && uncompressed != 0 {
110            return Err(invalid(offset, "directory has file data"));
111        }
112
113        if matches!(self.kind, EntryKind::SymbolicLink) && uncompressed == 0 {
114            return Err(invalid(offset, "empty symbolic-link target"));
115        }
116
117        Ok(CompletedMember {
118            header: self,
119            payload,
120            offset,
121        })
122    }
123}
124
125/// Final member metadata with a consistent method, CRC, and size tuple.
126pub struct CompletedMember<'a> {
127    header: PendingMember<'a>,
128    payload: MemberPayload,
129    offset: u64,
130}
131
132impl CompletedMember<'_> {
133    /// Serializes the local header with the final CRC and sizes.
134    pub fn local_header(&self) -> Vec<u8> {
135        let mut bytes = Vec::with_capacity(self.header.local_header_size());
136        push32(&mut bytes, signature::LOCAL);
137        self.append_common(&mut bytes, extra::ZIP64_LOCAL_SIZE);
138        self.append_name_and_sizes(&mut bytes, extra::ZIP64_LOCAL_SIZE);
139        bytes
140    }
141
142    /// Serializes the matching central-directory header.
143    pub fn central_header(&self) -> Vec<u8> {
144        let mut bytes = Vec::new();
145        self.append_central_header(&mut bytes);
146        bytes
147    }
148
149    /// Appends the matching central-directory header to `bytes`.
150    pub fn append_central_header(&self, bytes: &mut Vec<u8>) {
151        bytes.reserve(self.header.central_header_size());
152        push32(bytes, signature::CENTRAL);
153        push16(bytes, VERSION_MADE_BY);
154        self.append_common(bytes, extra::ZIP64_CENTRAL_SIZE);
155        push16(bytes, 0); // Comment length.
156        push16(bytes, 0); // Starting disk.
157        push16(bytes, 0); // Internal attributes.
158
159        let (file_type, permissions) = match self.header.kind {
160            EntryKind::File { executable: true } => (UnixFileType::Regular, 0o755),
161            EntryKind::File { executable: false } => (UnixFileType::Regular, 0o644),
162            EntryKind::Directory => (UnixFileType::Directory, 0o755),
163            EntryKind::SymbolicLink => (UnixFileType::SymbolicLink, 0o777),
164        };
165        let dos = if matches!(self.header.kind, EntryKind::Directory) {
166            ExternalAttributes::DOS_DIRECTORY
167        } else {
168            0
169        };
170        push32(
171            bytes,
172            (u32::from(u16::from(file_type) | permissions) << ExternalAttributes::UNIX_MODE_SHIFT)
173                | dos,
174        );
175        push32(bytes, u32::MAX);
176
177        self.append_name_and_sizes(bytes, extra::ZIP64_CENTRAL_SIZE);
178        push64(bytes, self.offset);
179    }
180
181    fn append_name_and_sizes(&self, bytes: &mut Vec<u8>, zip64_size: usize) {
182        bytes.extend_from_slice(self.header.path.as_bytes());
183        push16(bytes, u16::from(ExtraHeaderId::Zip64));
184        push16(bytes, zip64_size as u16);
185        push64(bytes, self.payload.fields().uncompressed);
186        push64(bytes, self.payload.fields().compressed);
187    }
188
189    fn append_common(&self, bytes: &mut Vec<u8>, zip64_size: usize) {
190        let header = MemberHeader {
191            version: version::ZIP64,
192            common: Common {
193                flags: GeneralPurposeFlags::UTF8,
194                method: self.header.method,
195            },
196            time: DEFAULT_TIME,
197            date: DEFAULT_DATE,
198            payload: PayloadFields {
199                crc: self.payload.fields().crc,
200                compressed: SizeField::Zip64,
201                uncompressed: SizeField::Zip64,
202            },
203        };
204        bytes.extend_from_slice(&header.to_bytes());
205        push16(bytes, self.header.path.len() as u16);
206        push16(bytes, (extra::HEADER_SIZE + zip64_size) as u16);
207    }
208}
209
210/// Serializes the ZIP64 end record, locator, and classic end record.
211///
212/// See [PKWARE APPNOTE 6.3.9](https://pkwaredownloads.blob.core.windows.net/pkware-general/Documentation/APPNOTE-6.3.9.TXT)
213/// sections 4.3.14 through 4.3.16 for the record layouts.
214pub fn end_records(count: u64, offset: u64, size: u64) -> Result<Vec<u8>, Error> {
215    let position = add(offset, size)?;
216    let mut bytes = Vec::with_capacity(size::ZIP64_END + size::ZIP64_LOCATOR + size::END);
217
218    // ZIP64 end of central directory record (APPNOTE 4.3.14): stores the
219    // entry count and central directory size and offset as 64-bit values.
220    push32(&mut bytes, signature::ZIP64_END);
221    // The size excludes the 12-byte signature/size prefix (APPNOTE 4.3.14.1).
222    push64(&mut bytes, size::ZIP64_END_BODY as u64);
223    push16(&mut bytes, VERSION_MADE_BY);
224    push16(&mut bytes, version::ZIP64);
225    push32(&mut bytes, 0); // This disk.
226    push32(&mut bytes, 0); // Disk containing the central directory.
227    push64(&mut bytes, count); // Entries on this disk.
228    push64(&mut bytes, count); // Total entries.
229    push64(&mut bytes, size);
230    push64(&mut bytes, offset);
231
232    // ZIP64 end of central directory locator (APPNOTE 4.3.15): points to
233    // the ZIP64 end record above. This single-volume archive uses disk 0.
234    push32(&mut bytes, signature::ZIP64_LOCATOR);
235    push32(&mut bytes, 0);
236    push64(&mut bytes, position);
237    push32(&mut bytes, 1); // Total disks.
238
239    // End of central directory record (APPNOTE 4.3.16): the required archive
240    // terminator. The maximum count, size, and offset values select the ZIP64
241    // fields above (APPNOTE 4.4.21 through 4.4.24).
242    push32(&mut bytes, signature::END);
243    push16(&mut bytes, 0);
244    push16(&mut bytes, 0);
245    push16(&mut bytes, u16::MAX);
246    push16(&mut bytes, u16::MAX);
247    push32(&mut bytes, u32::MAX);
248    push32(&mut bytes, u32::MAX);
249    push16(&mut bytes, 0); // No archive comment.
250
251    Ok(bytes)
252}
253
254fn push16(bytes: &mut Vec<u8>, value: u16) {
255    bytes.extend_from_slice(&value.to_le_bytes());
256}
257
258fn push32(bytes: &mut Vec<u8>, value: u32) {
259    bytes.extend_from_slice(&value.to_le_bytes());
260}
261
262fn push64(bytes: &mut Vec<u8>, value: u64) {
263    bytes.extend_from_slice(&value.to_le_bytes());
264}