Skip to main content

f_office_opc/
write.rs

1//! The package writer: a new package from the bytes of an original one and changes of its
2//! parts, in which every byte of the original that no change touches stays as it was.
3//!
4//! It splices the original ZIP file in place of writing it anew: it copies each entry that no
5//! change names, its local header, data and data descriptor, as raw bytes, and each of its
6//! central directory records with only the offset of its local header changed, and the bytes
7//! between them. The ZIP crate's own copy of a raw entry writes a new local header and a new
8//! central directory, so it does not keep those bytes (`tests::the_zip_writer_does_not_keep_the_bytes`).
9
10mod layout;
11#[cfg(test)]
12mod tests;
13
14use std::collections::BTreeSet;
15use std::fmt;
16use std::io::Write as _;
17use std::ops::Range;
18
19use flate2::Compression;
20use flate2::write::DeflateEncoder;
21
22use crate::{Limits, key, normalize};
23use layout::{CENTRAL_SIGNATURE, Entry, LOCAL_HEADER, LOCAL_SIGNATURE, Layout, u16_at};
24
25/// The flag of an entry whose name is in UTF-8 (APPNOTE.TXT, 4.4.4, bit 11).
26const UTF8_FLAG: u16 = 1 << 11;
27/// The compression method of data stored as it is.
28const STORED: u16 = 0;
29/// The compression method of deflated data.
30const DEFLATED: u16 = 8;
31/// The version of the ZIP format that an entry that the writer writes needs, and that a new
32/// entry is made by: 2.0, which has deflate.
33const VERSION_20: u16 = 20;
34/// The DOS date of a new entry: 1980-01-01, the first date that the format holds, so that the
35/// same changes always give the same bytes.
36const FIRST_DOS_DATE: u16 = (1 << 5) | 1;
37/// The most entries that a ZIP file without ZIP64 holds.
38const MAX_ENTRIES: usize = u16::MAX as usize - 1;
39
40/// A change of one part that [`write_package`] makes.
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum PartChange<'a> {
43    /// Replaces the bytes of the part `name`, which the package must hold, with `data`.
44    Replace {
45        /// The part's name, which may start with `/` and differ in the case of its ASCII
46        /// letters from the name in the package, as for [`crate::Package::part`].
47        name: &'a str,
48        /// The part's new bytes.
49        data: &'a [u8],
50    },
51    /// Adds the part `name`, which the package must not hold under an equivalent name, with
52    /// `data`. It changes neither `[Content_Types].xml` nor any relationships part: a caller
53    /// that adds a part changes those as well, with their own changes.
54    Add {
55        /// The part's name, written without a leading `/`.
56        name: &'a str,
57        /// The part's bytes.
58        data: &'a [u8],
59    },
60}
61
62impl PartChange<'_> {
63    /// The name of the part that the change names.
64    #[must_use]
65    pub const fn name(&self) -> &str {
66        match self {
67            Self::Replace { name, .. } | Self::Add { name, .. } => name,
68        }
69    }
70}
71
72/// Why [`write_package`] could not write a package.
73#[derive(Clone, Debug, PartialEq, Eq)]
74#[non_exhaustive]
75pub enum WriteError {
76    /// The original's ZIP records are not where its end record and central directory say.
77    Layout(LayoutFault),
78    /// The original uses ZIP64, which the writer does not write.
79    Zip64,
80    /// A [`PartChange::Replace`] names a part that the package does not hold.
81    NoSuchPart(String),
82    /// A [`PartChange::Add`] names a part that the package holds under an equivalent name.
83    PartExists(String),
84    /// Two changes name one part, or parts with equivalent names: the second one's name.
85    ChangedTwice(String),
86    /// The package would be larger than [`Limits::max_written_size`], or hold more bytes or
87    /// entries than a ZIP file without ZIP64 can.
88    TooLarge,
89    /// The deflate encoder failed.
90    Deflate,
91}
92
93/// What is wrong with the records of a ZIP file that the writer reads.
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95#[non_exhaustive]
96pub enum LayoutFault {
97    /// The file has no end of central directory record whose comment ends the file.
98    NoEndRecord,
99    /// The file spans more than one disk.
100    MultiDisk,
101    /// The central directory is not where the end record says, or a record of it does not read.
102    CentralDirectory,
103    /// A local file header is not where its central record says, or its entry does not fit.
104    LocalHeader,
105    /// Two entries' local records overlap.
106    Overlap,
107    /// A record ends before its fields.
108    Truncated,
109}
110
111impl fmt::Display for WriteError {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        match self {
114            Self::Layout(fault) => write!(f, "the package's ZIP records do not read: {fault}"),
115            Self::Zip64 => f.write_str("the package uses ZIP64, which the writer does not write"),
116            Self::NoSuchPart(name) => write!(f, "the package has no part {name}"),
117            Self::PartExists(name) => write!(f, "the package already has a part {name}"),
118            Self::ChangedTwice(name) => write!(f, "two changes name the part {name}"),
119            Self::TooLarge => f.write_str("the written package would be too large"),
120            Self::Deflate => f.write_str("the deflate encoder failed"),
121        }
122    }
123}
124
125impl fmt::Display for LayoutFault {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.write_str(match self {
128            Self::NoEndRecord => "it has no end of central directory record",
129            Self::MultiDisk => "it spans more than one disk",
130            Self::CentralDirectory => "its central directory does not read",
131            Self::LocalHeader => "a local file header is not where its central record says",
132            Self::Overlap => "two entries overlap",
133            Self::Truncated => "a record ends before its fields",
134        })
135    }
136}
137
138impl std::error::Error for WriteError {}
139
140/// A part's bytes as an entry holds them.
141#[derive(Debug)]
142struct Encoded {
143    /// The compression method.
144    method: u16,
145    /// The CRC-32 of the part's bytes.
146    crc: u32,
147    /// The part's size.
148    size: u32,
149    /// The bytes that the entry holds.
150    data: Vec<u8>,
151}
152
153/// What the changes do to the entries.
154#[derive(Debug)]
155struct Plan {
156    /// The new bytes of each entry of the original, by its index in the central directory, or
157    /// `None` for an entry that stays as it is.
158    replaced: Vec<Option<Encoded>>,
159    /// The name and the bytes of each new entry.
160    added: Vec<(Vec<u8>, Encoded)>,
161}
162
163/// Writes the package `original` with `changes`: each part that no change names keeps its
164/// bytes in the ZIP file, its local header, data, data descriptor and central record, but for
165/// the offset of its local header; so do the bytes between them and the end record's comment.
166/// With no change, the result is `original`, byte for byte.
167///
168/// A replaced part keeps its entry's place, name bytes, time, external attributes, the flag
169/// that its name is in UTF-8, its extra fields and its comment, and is stored again as it was,
170/// or deflated; it gets no data descriptor. An added part comes after the last entry, deflated,
171/// with the date 1980-01-01. Names compare as part names do ([`crate::Package::part`]); an
172/// entry whose name is neither ASCII nor flagged as UTF-8 matches no change.
173///
174/// # Errors
175///
176/// Returns [`WriteError::Layout`] or [`WriteError::Zip64`] for an original that the writer
177/// does not read, [`WriteError::NoSuchPart`], [`WriteError::PartExists`] or
178/// [`WriteError::ChangedTwice`] for changes that do not fit it, and [`WriteError::TooLarge`]
179/// for a package beyond [`Limits::max_written_size`].
180pub fn write_package(
181    original: &[u8],
182    changes: &[PartChange<'_>],
183    limits: &Limits,
184) -> Result<Vec<u8>, WriteError> {
185    let layout = layout::read(original)?;
186    let plan = plan(original, &layout, changes)?;
187    let limit = usize::try_from(limits.max_written_size).unwrap_or(usize::MAX);
188    let mut out = Output {
189        bytes: Vec::with_capacity(original.len()),
190        limit,
191    };
192    let (offsets, added) = write_entries(original, &layout, &plan, &mut out)?;
193    let central = out.offset()?;
194    for ((entry, replaced), offset) in layout.entries.iter().zip(&plan.replaced).zip(offsets) {
195        let record = slice(original, &entry.record)?;
196        out.push(&central_record(record, replaced.as_ref(), offset)?)?;
197    }
198    for ((name, encoded), offset) in plan.added.iter().zip(added) {
199        out.push(&new_central_record(name, encoded, offset)?)?;
200    }
201    let size = out.offset()? - central;
202    out.push(slice(original, &(layout.central.end..layout.end.start))?)?;
203    let end = end_record(
204        slice(original, &layout.end)?,
205        plan.added.len(),
206        (size, central),
207    )?;
208    out.push(&end)?;
209    Ok(out.bytes)
210}
211
212/// The written package, which may not grow beyond its limit.
213struct Output {
214    /// The bytes written so far.
215    bytes: Vec<u8>,
216    /// The most bytes that the package may have.
217    limit: usize,
218}
219
220impl Output {
221    /// Adds `piece`.
222    fn push(&mut self, piece: &[u8]) -> Result<(), WriteError> {
223        if self.bytes.len().saturating_add(piece.len()) > self.limit {
224            return Err(WriteError::TooLarge);
225        }
226        self.bytes.extend_from_slice(piece);
227        Ok(())
228    }
229
230    /// The offset of the next byte, which a ZIP file without ZIP64 must hold in 32 bits.
231    fn offset(&self) -> Result<u32, WriteError> {
232        u32::try_from(self.bytes.len()).map_err(|_| WriteError::TooLarge)
233    }
234}
235
236/// The bytes of `range` in `bytes`.
237fn slice<'b>(bytes: &'b [u8], range: &Range<usize>) -> Result<&'b [u8], WriteError> {
238    bytes
239        .get(range.clone())
240        .ok_or(WriteError::Layout(LayoutFault::Truncated))
241}
242
243/// What the changes do to the entries of `layout`.
244fn plan(original: &[u8], layout: &Layout, changes: &[PartChange<'_>]) -> Result<Plan, WriteError> {
245    let keys: Vec<Option<String>> = layout
246        .entries
247        .iter()
248        .map(|entry| entry_key(original, entry))
249        .collect();
250    let mut replaced: Vec<Option<Encoded>> = keys.iter().map(|_| None).collect();
251    let mut added = Vec::new();
252    let mut named = BTreeSet::new();
253    for change in changes {
254        let wanted = key(change.name());
255        if !named.insert(wanted.clone()) {
256            return Err(WriteError::ChangedTwice(change.name().to_owned()));
257        }
258        let found = keys
259            .iter()
260            .position(|key| key.as_deref() == Some(wanted.as_str()));
261        match (change, found) {
262            (PartChange::Replace { data, .. }, Some(index)) => {
263                let method = layout
264                    .entries
265                    .get(index)
266                    .and_then(|entry| u16_at(original, entry.record.start + 10));
267                let method = if method == Some(STORED) {
268                    STORED
269                } else {
270                    DEFLATED
271                };
272                if let Some(slot) = replaced.get_mut(index) {
273                    *slot = Some(encode(data, method)?);
274                }
275            }
276            (PartChange::Replace { name, .. }, None) => {
277                return Err(WriteError::NoSuchPart((*name).to_owned()));
278            }
279            (PartChange::Add { name, .. }, Some(_)) => {
280                return Err(WriteError::PartExists((*name).to_owned()));
281            }
282            (PartChange::Add { name, data }, None) => {
283                added.push((normalize(name).into_bytes(), encode(data, DEFLATED)?));
284            }
285        }
286    }
287    if layout.entries.len() + added.len() > MAX_ENTRIES {
288        return Err(WriteError::TooLarge);
289    }
290    Ok(Plan { replaced, added })
291}
292
293/// The key of an entry's name ([`key`]), or `None` for a folder and for a name that is neither
294/// ASCII nor flagged as UTF-8.
295fn entry_key(original: &[u8], entry: &Entry) -> Option<String> {
296    let name = original.get(entry.name.clone())?;
297    let utf8 = u16_at(original, entry.record.start + 8)? & UTF8_FLAG != 0;
298    if !utf8 && !name.is_ascii() {
299        return None;
300    }
301    let name = std::str::from_utf8(name).ok()?;
302    (!name.ends_with('/')).then(|| key(name))
303}
304
305/// A part's bytes stored as they are, or deflated, with their CRC-32 and size.
306fn encode(data: &[u8], method: u16) -> Result<Encoded, WriteError> {
307    let size = u32::try_from(data.len()).map_err(|_| WriteError::TooLarge)?;
308    let mut crc = flate2::Crc::new();
309    crc.update(data);
310    let stored = if method == STORED {
311        data.to_vec()
312    } else {
313        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
314        encoder
315            .write_all(data)
316            .and_then(|()| encoder.finish())
317            .map_err(|_| WriteError::Deflate)?
318    };
319    u32::try_from(stored.len()).map_err(|_| WriteError::TooLarge)?;
320    Ok(Encoded {
321        method,
322        crc: crc.sum(),
323        size,
324        data: stored,
325    })
326}
327
328/// Writes the local entries: each of the original in its place, as it is or with its new bytes,
329/// with the bytes before and between them, then each new one. Gives the new offset of the local
330/// header of each entry of the original and of each new entry.
331fn write_entries(
332    original: &[u8],
333    layout: &Layout,
334    plan: &Plan,
335    out: &mut Output,
336) -> Result<(Vec<u32>, Vec<u32>), WriteError> {
337    let mut order: Vec<(usize, &Entry)> = layout.entries.iter().enumerate().collect();
338    order.sort_by_key(|(_, entry)| entry.local.start);
339    let mut offsets = vec![0; layout.entries.len()];
340    let mut cursor = 0;
341    for (index, entry) in order {
342        out.push(slice(original, &(cursor..entry.local.start))?)?;
343        if let Some(offset) = offsets.get_mut(index) {
344            *offset = out.offset()?;
345        }
346        match plan.replaced.get(index).and_then(Option::as_ref) {
347            Some(encoded) => out.push(&changed_local(original, entry, encoded)?)?,
348            None => out.push(slice(original, &entry.local)?)?,
349        }
350        cursor = entry.local.end;
351    }
352    out.push(slice(original, &(cursor..layout.central.start))?)?;
353    let mut added = Vec::with_capacity(plan.added.len());
354    for (name, encoded) in &plan.added {
355        added.push(out.offset()?);
356        out.push(&local_header(name, encoded, &Fields::new_entry(name))?)?;
357        out.push(&encoded.data)?;
358    }
359    Ok((offsets, added))
360}
361
362/// The fields of an entry that its local header and central record share, besides the
363/// encoded part.
364struct Fields<'f> {
365    /// The version of the format that the entry needs.
366    needed: u16,
367    /// The general purpose flags.
368    flags: u16,
369    /// The DOS time.
370    time: u16,
371    /// The DOS date.
372    date: u16,
373    /// The extra field of the local header.
374    local_extra: &'f [u8],
375}
376
377impl<'f> Fields<'f> {
378    /// The fields of a new entry named `name`.
379    fn new_entry(name: &[u8]) -> Self {
380        Self {
381            needed: VERSION_20,
382            flags: if name.is_ascii() { 0 } else { UTF8_FLAG },
383            time: 0,
384            date: FIRST_DOS_DATE,
385            local_extra: &[],
386        }
387    }
388
389    /// The fields of a changed entry of the original: those of its central record, with the
390    /// version that the writer's entry needs and only the flag that its name is in UTF-8.
391    fn changed(original: &'f [u8], entry: &Entry) -> Result<Self, WriteError> {
392        let field = |at: usize| {
393            u16_at(original, entry.record.start + at)
394                .ok_or(WriteError::Layout(LayoutFault::Truncated))
395        };
396        Ok(Self {
397            needed: field(6)?.max(VERSION_20),
398            flags: field(8)? & UTF8_FLAG,
399            time: field(12)?,
400            date: field(14)?,
401            local_extra: slice(original, &entry.local_extra)?,
402        })
403    }
404}
405
406/// A local file header and the bytes of a changed entry of the original.
407fn changed_local(original: &[u8], entry: &Entry, encoded: &Encoded) -> Result<Vec<u8>, WriteError> {
408    let fields = Fields::changed(original, entry)?;
409    let mut bytes = local_header(slice(original, &entry.name)?, encoded, &fields)?;
410    bytes.extend_from_slice(&encoded.data);
411    Ok(bytes)
412}
413
414/// The local file header of an entry named `name` with the bytes `encoded`.
415fn local_header(
416    name: &[u8],
417    encoded: &Encoded,
418    fields: &Fields<'_>,
419) -> Result<Vec<u8>, WriteError> {
420    let mut header = Vec::with_capacity(LOCAL_HEADER + name.len());
421    header.extend_from_slice(&LOCAL_SIGNATURE.to_le_bytes());
422    for value in [
423        fields.needed,
424        fields.flags,
425        encoded.method,
426        fields.time,
427        fields.date,
428    ] {
429        header.extend_from_slice(&value.to_le_bytes());
430    }
431    for value in [encoded.crc, length32(&encoded.data)?, encoded.size] {
432        header.extend_from_slice(&value.to_le_bytes());
433    }
434    header.extend_from_slice(&length16(name)?.to_le_bytes());
435    header.extend_from_slice(&length16(fields.local_extra)?.to_le_bytes());
436    header.extend_from_slice(name);
437    header.extend_from_slice(fields.local_extra);
438    Ok(header)
439}
440
441/// The central directory record of an entry of the original: its bytes with the new offset of
442/// its local header, and for a changed entry also its version needed, flags, method, CRC and
443/// sizes.
444fn central_record(
445    record: &[u8],
446    replaced: Option<&Encoded>,
447    offset: u32,
448) -> Result<Vec<u8>, WriteError> {
449    let mut bytes = record.to_vec();
450    set(&mut bytes, 42, &offset.to_le_bytes())?;
451    if let Some(encoded) = replaced {
452        let needed = u16_at(record, 6).map_or(VERSION_20, |needed| needed.max(VERSION_20));
453        let flags = u16_at(record, 8).unwrap_or(0) & UTF8_FLAG;
454        set(&mut bytes, 6, &needed.to_le_bytes())?;
455        set(&mut bytes, 8, &flags.to_le_bytes())?;
456        set(&mut bytes, 10, &encoded.method.to_le_bytes())?;
457        set(&mut bytes, 16, &encoded.crc.to_le_bytes())?;
458        set(&mut bytes, 20, &length32(&encoded.data)?.to_le_bytes())?;
459        set(&mut bytes, 24, &encoded.size.to_le_bytes())?;
460    }
461    Ok(bytes)
462}
463
464/// The central directory record of a new entry named `name`.
465fn new_central_record(name: &[u8], encoded: &Encoded, offset: u32) -> Result<Vec<u8>, WriteError> {
466    let fields = Fields::new_entry(name);
467    let local = local_header(name, encoded, &fields)?;
468    let mut record = Vec::with_capacity(local.len() + 16);
469    record.extend_from_slice(&CENTRAL_SIGNATURE.to_le_bytes());
470    record.extend_from_slice(&VERSION_20.to_le_bytes());
471    // The local header's fields from its version needed to its extra field's length.
472    record.extend_from_slice(slice(&local, &(4..LOCAL_HEADER))?);
473    // No comment, disk 0, no internal or external attributes, then the offset.
474    record.extend_from_slice(&[0; 10]);
475    record.extend_from_slice(&offset.to_le_bytes());
476    record.extend_from_slice(name);
477    Ok(record)
478}
479
480/// The end of central directory record `original` with `added` more entries and the central
481/// directory of `size` bytes at `offset`, and its comment.
482fn end_record(
483    original: &[u8],
484    added: usize,
485    (size, offset): (u32, u32),
486) -> Result<Vec<u8>, WriteError> {
487    let mut bytes = original.to_vec();
488    let entries = u16_at(original, 10)
489        .map(usize::from)
490        .ok_or(WriteError::Layout(LayoutFault::Truncated))?
491        + added;
492    let entries = u16::try_from(entries).map_err(|_| WriteError::TooLarge)?;
493    set(&mut bytes, 8, &entries.to_le_bytes())?;
494    set(&mut bytes, 10, &entries.to_le_bytes())?;
495    set(&mut bytes, 12, &size.to_le_bytes())?;
496    set(&mut bytes, 16, &offset.to_le_bytes())?;
497    Ok(bytes)
498}
499
500/// Writes `value` into `bytes` at `at`.
501fn set(bytes: &mut [u8], at: usize, value: &[u8]) -> Result<(), WriteError> {
502    bytes
503        .get_mut(at..at + value.len())
504        .ok_or(WriteError::Layout(LayoutFault::Truncated))?
505        .copy_from_slice(value);
506    Ok(())
507}
508
509/// The length of `bytes` as a field of 16 bits.
510fn length16(bytes: &[u8]) -> Result<u16, WriteError> {
511    u16::try_from(bytes.len()).map_err(|_| WriteError::TooLarge)
512}
513
514/// The length of `bytes` as a field of 32 bits.
515fn length32(bytes: &[u8]) -> Result<u32, WriteError> {
516    u32::try_from(bytes.len()).map_err(|_| WriteError::TooLarge)
517}