f-office-opc 0.2.2

Open Packaging Conventions container: ZIP package and relationships, with input limits.
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
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
//! The package writer: a new package from the bytes of an original one and changes of its
//! parts, in which every byte of the original that no change touches stays as it was.
//!
//! It splices the original ZIP file in place of writing it anew: it copies each entry that no
//! change names, its local header, data and data descriptor, as raw bytes, and each of its
//! central directory records with only the offset of its local header changed, and the bytes
//! between them. The ZIP crate's own copy of a raw entry writes a new local header and a new
//! central directory, so it does not keep those bytes (`tests::the_zip_writer_does_not_keep_the_bytes`).

mod layout;
#[cfg(test)]
mod tests;

use std::collections::BTreeSet;
use std::fmt;
use std::io::Write as _;
use std::ops::Range;

use flate2::Compression;
use flate2::write::DeflateEncoder;

use crate::{Limits, key, normalize};
use layout::{CENTRAL_SIGNATURE, Entry, LOCAL_HEADER, LOCAL_SIGNATURE, Layout, u16_at};

/// The flag of an entry whose name is in UTF-8 (APPNOTE.TXT, 4.4.4, bit 11).
const UTF8_FLAG: u16 = 1 << 11;
/// The compression method of data stored as it is.
const STORED: u16 = 0;
/// The compression method of deflated data.
const DEFLATED: u16 = 8;
/// The version of the ZIP format that an entry that the writer writes needs, and that a new
/// entry is made by: 2.0, which has deflate.
const VERSION_20: u16 = 20;
/// The DOS date of a new entry: 1980-01-01, the first date that the format holds, so that the
/// same changes always give the same bytes.
const FIRST_DOS_DATE: u16 = (1 << 5) | 1;
/// The most entries that a ZIP file without ZIP64 holds.
const MAX_ENTRIES: usize = u16::MAX as usize - 1;

/// A change of one part that [`write_package`] makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PartChange<'a> {
    /// Replaces the bytes of the part `name`, which the package must hold, with `data`.
    Replace {
        /// The part's name, which may start with `/` and differ in the case of its ASCII
        /// letters from the name in the package, as for [`crate::Package::part`].
        name: &'a str,
        /// The part's new bytes.
        data: &'a [u8],
    },
    /// Adds the part `name`, which the package must not hold under an equivalent name, with
    /// `data`. It changes neither `[Content_Types].xml` nor any relationships part: a caller
    /// that adds a part changes those as well, with their own changes.
    Add {
        /// The part's name, written without a leading `/`.
        name: &'a str,
        /// The part's bytes.
        data: &'a [u8],
    },
}

impl PartChange<'_> {
    /// The name of the part that the change names.
    #[must_use]
    pub const fn name(&self) -> &str {
        match self {
            Self::Replace { name, .. } | Self::Add { name, .. } => name,
        }
    }
}

/// Why [`write_package`] could not write a package.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum WriteError {
    /// The original's ZIP records are not where its end record and central directory say.
    Layout(LayoutFault),
    /// The original uses ZIP64, which the writer does not write.
    Zip64,
    /// A [`PartChange::Replace`] names a part that the package does not hold.
    NoSuchPart(String),
    /// A [`PartChange::Add`] names a part that the package holds under an equivalent name.
    PartExists(String),
    /// Two changes name one part, or parts with equivalent names: the second one's name.
    ChangedTwice(String),
    /// The package would be larger than [`Limits::max_written_size`], or hold more bytes or
    /// entries than a ZIP file without ZIP64 can.
    TooLarge,
    /// The deflate encoder failed.
    Deflate,
}

/// What is wrong with the records of a ZIP file that the writer reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum LayoutFault {
    /// The file has no end of central directory record whose comment ends the file.
    NoEndRecord,
    /// The file spans more than one disk.
    MultiDisk,
    /// The central directory is not where the end record says, or a record of it does not read.
    CentralDirectory,
    /// A local file header is not where its central record says, or its entry does not fit.
    LocalHeader,
    /// Two entries' local records overlap.
    Overlap,
    /// A record ends before its fields.
    Truncated,
}

impl fmt::Display for WriteError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Layout(fault) => write!(f, "the package's ZIP records do not read: {fault}"),
            Self::Zip64 => f.write_str("the package uses ZIP64, which the writer does not write"),
            Self::NoSuchPart(name) => write!(f, "the package has no part {name}"),
            Self::PartExists(name) => write!(f, "the package already has a part {name}"),
            Self::ChangedTwice(name) => write!(f, "two changes name the part {name}"),
            Self::TooLarge => f.write_str("the written package would be too large"),
            Self::Deflate => f.write_str("the deflate encoder failed"),
        }
    }
}

impl fmt::Display for LayoutFault {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NoEndRecord => "it has no end of central directory record",
            Self::MultiDisk => "it spans more than one disk",
            Self::CentralDirectory => "its central directory does not read",
            Self::LocalHeader => "a local file header is not where its central record says",
            Self::Overlap => "two entries overlap",
            Self::Truncated => "a record ends before its fields",
        })
    }
}

impl std::error::Error for WriteError {}

/// A part's bytes as an entry holds them.
#[derive(Debug)]
struct Encoded {
    /// The compression method.
    method: u16,
    /// The CRC-32 of the part's bytes.
    crc: u32,
    /// The part's size.
    size: u32,
    /// The bytes that the entry holds.
    data: Vec<u8>,
}

/// What the changes do to the entries.
#[derive(Debug)]
struct Plan {
    /// The new bytes of each entry of the original, by its index in the central directory, or
    /// `None` for an entry that stays as it is.
    replaced: Vec<Option<Encoded>>,
    /// The name and the bytes of each new entry.
    added: Vec<(Vec<u8>, Encoded)>,
}

/// Writes the package `original` with `changes`: each part that no change names keeps its
/// bytes in the ZIP file, its local header, data, data descriptor and central record, but for
/// the offset of its local header; so do the bytes between them and the end record's comment.
/// With no change, the result is `original`, byte for byte.
///
/// A replaced part keeps its entry's place, name bytes, time, external attributes, the flag
/// that its name is in UTF-8, its extra fields and its comment, and is stored again as it was,
/// or deflated; it gets no data descriptor. An added part comes after the last entry, deflated,
/// with the date 1980-01-01. Names compare as part names do ([`crate::Package::part`]); an
/// entry whose name is neither ASCII nor flagged as UTF-8 matches no change.
///
/// # Errors
///
/// Returns [`WriteError::Layout`] or [`WriteError::Zip64`] for an original that the writer
/// does not read, [`WriteError::NoSuchPart`], [`WriteError::PartExists`] or
/// [`WriteError::ChangedTwice`] for changes that do not fit it, and [`WriteError::TooLarge`]
/// for a package beyond [`Limits::max_written_size`].
pub fn write_package(
    original: &[u8],
    changes: &[PartChange<'_>],
    limits: &Limits,
) -> Result<Vec<u8>, WriteError> {
    let layout = layout::read(original)?;
    let plan = plan(original, &layout, changes)?;
    let limit = usize::try_from(limits.max_written_size).unwrap_or(usize::MAX);
    let mut out = Output {
        bytes: Vec::with_capacity(original.len()),
        limit,
    };
    let (offsets, added) = write_entries(original, &layout, &plan, &mut out)?;
    let central = out.offset()?;
    for ((entry, replaced), offset) in layout.entries.iter().zip(&plan.replaced).zip(offsets) {
        let record = slice(original, &entry.record)?;
        out.push(&central_record(record, replaced.as_ref(), offset)?)?;
    }
    for ((name, encoded), offset) in plan.added.iter().zip(added) {
        out.push(&new_central_record(name, encoded, offset)?)?;
    }
    let size = out.offset()? - central;
    out.push(slice(original, &(layout.central.end..layout.end.start))?)?;
    let end = end_record(
        slice(original, &layout.end)?,
        plan.added.len(),
        (size, central),
    )?;
    out.push(&end)?;
    Ok(out.bytes)
}

/// The written package, which may not grow beyond its limit.
struct Output {
    /// The bytes written so far.
    bytes: Vec<u8>,
    /// The most bytes that the package may have.
    limit: usize,
}

impl Output {
    /// Adds `piece`.
    fn push(&mut self, piece: &[u8]) -> Result<(), WriteError> {
        if self.bytes.len().saturating_add(piece.len()) > self.limit {
            return Err(WriteError::TooLarge);
        }
        self.bytes.extend_from_slice(piece);
        Ok(())
    }

    /// The offset of the next byte, which a ZIP file without ZIP64 must hold in 32 bits.
    fn offset(&self) -> Result<u32, WriteError> {
        u32::try_from(self.bytes.len()).map_err(|_| WriteError::TooLarge)
    }
}

/// The bytes of `range` in `bytes`.
fn slice<'b>(bytes: &'b [u8], range: &Range<usize>) -> Result<&'b [u8], WriteError> {
    bytes
        .get(range.clone())
        .ok_or(WriteError::Layout(LayoutFault::Truncated))
}

/// What the changes do to the entries of `layout`.
fn plan(original: &[u8], layout: &Layout, changes: &[PartChange<'_>]) -> Result<Plan, WriteError> {
    let keys: Vec<Option<String>> = layout
        .entries
        .iter()
        .map(|entry| entry_key(original, entry))
        .collect();
    let mut replaced: Vec<Option<Encoded>> = keys.iter().map(|_| None).collect();
    let mut added = Vec::new();
    let mut named = BTreeSet::new();
    for change in changes {
        let wanted = key(change.name());
        if !named.insert(wanted.clone()) {
            return Err(WriteError::ChangedTwice(change.name().to_owned()));
        }
        let found = keys
            .iter()
            .position(|key| key.as_deref() == Some(wanted.as_str()));
        match (change, found) {
            (PartChange::Replace { data, .. }, Some(index)) => {
                let method = layout
                    .entries
                    .get(index)
                    .and_then(|entry| u16_at(original, entry.record.start + 10));
                let method = if method == Some(STORED) {
                    STORED
                } else {
                    DEFLATED
                };
                if let Some(slot) = replaced.get_mut(index) {
                    *slot = Some(encode(data, method)?);
                }
            }
            (PartChange::Replace { name, .. }, None) => {
                return Err(WriteError::NoSuchPart((*name).to_owned()));
            }
            (PartChange::Add { name, .. }, Some(_)) => {
                return Err(WriteError::PartExists((*name).to_owned()));
            }
            (PartChange::Add { name, data }, None) => {
                added.push((normalize(name).into_bytes(), encode(data, DEFLATED)?));
            }
        }
    }
    if layout.entries.len() + added.len() > MAX_ENTRIES {
        return Err(WriteError::TooLarge);
    }
    Ok(Plan { replaced, added })
}

/// The key of an entry's name ([`key`]), or `None` for a folder and for a name that is neither
/// ASCII nor flagged as UTF-8.
fn entry_key(original: &[u8], entry: &Entry) -> Option<String> {
    let name = original.get(entry.name.clone())?;
    let utf8 = u16_at(original, entry.record.start + 8)? & UTF8_FLAG != 0;
    if !utf8 && !name.is_ascii() {
        return None;
    }
    let name = std::str::from_utf8(name).ok()?;
    (!name.ends_with('/')).then(|| key(name))
}

/// A part's bytes stored as they are, or deflated, with their CRC-32 and size.
fn encode(data: &[u8], method: u16) -> Result<Encoded, WriteError> {
    let size = u32::try_from(data.len()).map_err(|_| WriteError::TooLarge)?;
    let mut crc = flate2::Crc::new();
    crc.update(data);
    let stored = if method == STORED {
        data.to_vec()
    } else {
        let mut encoder = DeflateEncoder::new(Vec::new(), Compression::default());
        encoder
            .write_all(data)
            .and_then(|()| encoder.finish())
            .map_err(|_| WriteError::Deflate)?
    };
    u32::try_from(stored.len()).map_err(|_| WriteError::TooLarge)?;
    Ok(Encoded {
        method,
        crc: crc.sum(),
        size,
        data: stored,
    })
}

/// Writes the local entries: each of the original in its place, as it is or with its new bytes,
/// with the bytes before and between them, then each new one. Gives the new offset of the local
/// header of each entry of the original and of each new entry.
fn write_entries(
    original: &[u8],
    layout: &Layout,
    plan: &Plan,
    out: &mut Output,
) -> Result<(Vec<u32>, Vec<u32>), WriteError> {
    let mut order: Vec<(usize, &Entry)> = layout.entries.iter().enumerate().collect();
    order.sort_by_key(|(_, entry)| entry.local.start);
    let mut offsets = vec![0; layout.entries.len()];
    let mut cursor = 0;
    for (index, entry) in order {
        out.push(slice(original, &(cursor..entry.local.start))?)?;
        if let Some(offset) = offsets.get_mut(index) {
            *offset = out.offset()?;
        }
        match plan.replaced.get(index).and_then(Option::as_ref) {
            Some(encoded) => out.push(&changed_local(original, entry, encoded)?)?,
            None => out.push(slice(original, &entry.local)?)?,
        }
        cursor = entry.local.end;
    }
    out.push(slice(original, &(cursor..layout.central.start))?)?;
    let mut added = Vec::with_capacity(plan.added.len());
    for (name, encoded) in &plan.added {
        added.push(out.offset()?);
        out.push(&local_header(name, encoded, &Fields::new_entry(name))?)?;
        out.push(&encoded.data)?;
    }
    Ok((offsets, added))
}

/// The fields of an entry that its local header and central record share, besides the
/// encoded part.
struct Fields<'f> {
    /// The version of the format that the entry needs.
    needed: u16,
    /// The general purpose flags.
    flags: u16,
    /// The DOS time.
    time: u16,
    /// The DOS date.
    date: u16,
    /// The extra field of the local header.
    local_extra: &'f [u8],
}

impl<'f> Fields<'f> {
    /// The fields of a new entry named `name`.
    fn new_entry(name: &[u8]) -> Self {
        Self {
            needed: VERSION_20,
            flags: if name.is_ascii() { 0 } else { UTF8_FLAG },
            time: 0,
            date: FIRST_DOS_DATE,
            local_extra: &[],
        }
    }

    /// The fields of a changed entry of the original: those of its central record, with the
    /// version that the writer's entry needs and only the flag that its name is in UTF-8.
    fn changed(original: &'f [u8], entry: &Entry) -> Result<Self, WriteError> {
        let field = |at: usize| {
            u16_at(original, entry.record.start + at)
                .ok_or(WriteError::Layout(LayoutFault::Truncated))
        };
        Ok(Self {
            needed: field(6)?.max(VERSION_20),
            flags: field(8)? & UTF8_FLAG,
            time: field(12)?,
            date: field(14)?,
            local_extra: slice(original, &entry.local_extra)?,
        })
    }
}

/// A local file header and the bytes of a changed entry of the original.
fn changed_local(original: &[u8], entry: &Entry, encoded: &Encoded) -> Result<Vec<u8>, WriteError> {
    let fields = Fields::changed(original, entry)?;
    let mut bytes = local_header(slice(original, &entry.name)?, encoded, &fields)?;
    bytes.extend_from_slice(&encoded.data);
    Ok(bytes)
}

/// The local file header of an entry named `name` with the bytes `encoded`.
fn local_header(
    name: &[u8],
    encoded: &Encoded,
    fields: &Fields<'_>,
) -> Result<Vec<u8>, WriteError> {
    let mut header = Vec::with_capacity(LOCAL_HEADER + name.len());
    header.extend_from_slice(&LOCAL_SIGNATURE.to_le_bytes());
    for value in [
        fields.needed,
        fields.flags,
        encoded.method,
        fields.time,
        fields.date,
    ] {
        header.extend_from_slice(&value.to_le_bytes());
    }
    for value in [encoded.crc, length32(&encoded.data)?, encoded.size] {
        header.extend_from_slice(&value.to_le_bytes());
    }
    header.extend_from_slice(&length16(name)?.to_le_bytes());
    header.extend_from_slice(&length16(fields.local_extra)?.to_le_bytes());
    header.extend_from_slice(name);
    header.extend_from_slice(fields.local_extra);
    Ok(header)
}

/// The central directory record of an entry of the original: its bytes with the new offset of
/// its local header, and for a changed entry also its version needed, flags, method, CRC and
/// sizes.
fn central_record(
    record: &[u8],
    replaced: Option<&Encoded>,
    offset: u32,
) -> Result<Vec<u8>, WriteError> {
    let mut bytes = record.to_vec();
    set(&mut bytes, 42, &offset.to_le_bytes())?;
    if let Some(encoded) = replaced {
        let needed = u16_at(record, 6).map_or(VERSION_20, |needed| needed.max(VERSION_20));
        let flags = u16_at(record, 8).unwrap_or(0) & UTF8_FLAG;
        set(&mut bytes, 6, &needed.to_le_bytes())?;
        set(&mut bytes, 8, &flags.to_le_bytes())?;
        set(&mut bytes, 10, &encoded.method.to_le_bytes())?;
        set(&mut bytes, 16, &encoded.crc.to_le_bytes())?;
        set(&mut bytes, 20, &length32(&encoded.data)?.to_le_bytes())?;
        set(&mut bytes, 24, &encoded.size.to_le_bytes())?;
    }
    Ok(bytes)
}

/// The central directory record of a new entry named `name`.
fn new_central_record(name: &[u8], encoded: &Encoded, offset: u32) -> Result<Vec<u8>, WriteError> {
    let fields = Fields::new_entry(name);
    let local = local_header(name, encoded, &fields)?;
    let mut record = Vec::with_capacity(local.len() + 16);
    record.extend_from_slice(&CENTRAL_SIGNATURE.to_le_bytes());
    record.extend_from_slice(&VERSION_20.to_le_bytes());
    // The local header's fields from its version needed to its extra field's length.
    record.extend_from_slice(slice(&local, &(4..LOCAL_HEADER))?);
    // No comment, disk 0, no internal or external attributes, then the offset.
    record.extend_from_slice(&[0; 10]);
    record.extend_from_slice(&offset.to_le_bytes());
    record.extend_from_slice(name);
    Ok(record)
}

/// The end of central directory record `original` with `added` more entries and the central
/// directory of `size` bytes at `offset`, and its comment.
fn end_record(
    original: &[u8],
    added: usize,
    (size, offset): (u32, u32),
) -> Result<Vec<u8>, WriteError> {
    let mut bytes = original.to_vec();
    let entries = u16_at(original, 10)
        .map(usize::from)
        .ok_or(WriteError::Layout(LayoutFault::Truncated))?
        + added;
    let entries = u16::try_from(entries).map_err(|_| WriteError::TooLarge)?;
    set(&mut bytes, 8, &entries.to_le_bytes())?;
    set(&mut bytes, 10, &entries.to_le_bytes())?;
    set(&mut bytes, 12, &size.to_le_bytes())?;
    set(&mut bytes, 16, &offset.to_le_bytes())?;
    Ok(bytes)
}

/// Writes `value` into `bytes` at `at`.
fn set(bytes: &mut [u8], at: usize, value: &[u8]) -> Result<(), WriteError> {
    bytes
        .get_mut(at..at + value.len())
        .ok_or(WriteError::Layout(LayoutFault::Truncated))?
        .copy_from_slice(value);
    Ok(())
}

/// The length of `bytes` as a field of 16 bits.
fn length16(bytes: &[u8]) -> Result<u16, WriteError> {
    u16::try_from(bytes.len()).map_err(|_| WriteError::TooLarge)
}

/// The length of `bytes` as a field of 32 bits.
fn length32(bytes: &[u8]) -> Result<u32, WriteError> {
    u32::try_from(bytes.len()).map_err(|_| WriteError::TooLarge)
}