Skip to main content

f_office_opc/
lib.rs

1//! Open Packaging Conventions container (ECMA-376 Part 2).
2//!
3//! This crate reads the ZIP package that holds every Office Open XML file, with its
4//! relationships. It enforces input limits on the size of each part, the total size, the
5//! compression ratio and the number of entries. It also writes a package with changed or added
6//! parts ([`write_package`]), in which every byte that no change touches stays as it was.
7
8use std::collections::BTreeMap;
9use std::collections::btree_map::Entry;
10use std::fmt;
11use std::io::Read;
12#[cfg(not(target_arch = "wasm32"))]
13use std::path::Path;
14use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
15use std::sync::{Arc, Mutex, OnceLock};
16
17use f_office_xml::Document;
18
19mod error;
20mod source;
21#[cfg(any(test, feature = "testing"))]
22pub mod testing;
23mod write;
24
25pub use error::{Error, Limit, ZipFault};
26/// The limits of each XML part, which [`Limits::xml`] holds.
27pub use f_office_xml::Limits as XmlLimits;
28pub use source::RandomAccessRead;
29pub use write::{LayoutFault, PartChange, WriteError, write_package};
30
31use source::{Backing, BackingReader};
32
33const RELATIONSHIPS_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
34
35/// Limits that protect the reader against hostile packages: those of the ZIP file, and those of
36/// each XML part, which the package keeps for the readers of its parts ([`Package::limits`]).
37/// Start from [`Limits::default`] and set the limits that differ, so that a new limit breaks no
38/// caller.
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40#[non_exhaustive]
41pub struct Limits {
42    /// The largest uncompressed part, in bytes.
43    pub max_part_size: u64,
44    /// The largest uncompressed total of all parts, in bytes.
45    pub max_total_size: u64,
46    /// The most entries in the ZIP file.
47    pub max_entries: usize,
48    /// The highest ratio of uncompressed to compressed size for parts above 1 MiB.
49    pub max_ratio: u64,
50    /// The limits of each XML part: the package's relationships parts and every part that a
51    /// reader of the package parses.
52    pub xml: XmlLimits,
53    /// The largest package that [`write_package`] writes, in bytes.
54    pub max_written_size: u64,
55}
56
57impl Default for Limits {
58    fn default() -> Self {
59        Self {
60            max_part_size: 256 << 20,
61            max_total_size: 1 << 30,
62            max_entries: 20_000,
63            max_ratio: 1_000,
64            xml: XmlLimits::default(),
65            max_written_size: 1 << 30,
66        }
67    }
68}
69
70impl Limits {
71    /// Limits tuned for memory-constrained devices such as phones and browser tabs
72    /// (32 MiB max part, 128 MiB max total, 500k XML nodes, 64 MiB max written package).
73    #[must_use]
74    pub const fn mobile() -> Self {
75        Self {
76            max_part_size: 32 << 20,
77            max_total_size: 128 << 20,
78            max_entries: 10_000,
79            max_ratio: 1_000,
80            xml: XmlLimits::mobile(),
81            max_written_size: 64 << 20,
82        }
83    }
84}
85
86/// One relationship from a source part to a target.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct Relationship {
89    /// The relationship ID, such as `rId1`.
90    pub id: String,
91    /// The relationship type URI.
92    pub rel_type: String,
93    /// The target part name, resolved against the source part, or the URI of an external target.
94    pub target: String,
95    /// Whether the target is outside the package.
96    pub external: bool,
97}
98
99/// What one relationships part holds, as [`Package::relationships`] reads it.
100#[derive(Clone, Debug, Default, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct RelationshipsPart {
103    /// The part's name as the package writes it, without a leading `/`, such as
104    /// `word/_rels/document.xml.rels`; empty when the package has no such part.
105    pub name: String,
106    /// The relationships, in the order of the part.
107    pub relationships: Vec<Relationship>,
108    /// The namespace prefixes that the part uses without a declaration, each once
109    /// ([`Document::undeclared_prefixes`]): a relationship written with one of them is not
110    /// among [`RelationshipsPart::relationships`].
111    pub undeclared_prefixes: Vec<String>,
112}
113
114/// What a source without a relationships part has.
115static NO_RELATIONSHIPS: RelationshipsPart = RelationshipsPart {
116    name: String::new(),
117    relationships: Vec::new(),
118    undeclared_prefixes: Vec::new(),
119};
120
121impl Relationship {
122    /// The first of `relationships` with the ID `id` whose target is a part of the package.
123    #[must_use]
124    pub fn by_id<'r>(relationships: &'r [Self], id: &str) -> Option<&'r Self> {
125        relationships
126            .iter()
127            .find(|rel| rel.id == id && !rel.external)
128    }
129
130    /// The first of `relationships` whose type ends with `suffix`, such as `/styles`, and whose
131    /// target is a part of the package. The suffix matches the type in the strict and in the
132    /// transitional namespace.
133    #[must_use]
134    pub fn by_type<'r>(relationships: &'r [Self], suffix: &str) -> Option<&'r Self> {
135        relationships
136            .iter()
137            .find(|rel| rel.rel_type.ends_with(suffix) && !rel.external)
138    }
139}
140
141/// An indexed ZIP package whose parts decompress lazily on demand.
142///
143/// Opening a package reads only the ZIP central directory and validates [`Limits`] without
144/// inflating any part bytes. Unused parts (such as thumbnails, embedded workbooks, or unvisited
145/// media) consume no memory.
146#[derive(Clone, Default)]
147pub struct Package {
148    /// Indexed ZIP archive kept open for O(1) lazy entry decompression.
149    archive: Arc<Mutex<Option<zip::ZipArchive<BackingReader>>>>,
150    /// The parts by their keys ([`key`]).
151    parts: BTreeMap<String, Part>,
152    /// The relationships that each relationships part holds, by the part's key, read on their
153    /// first use and kept.
154    relationships: BTreeMap<String, OnceLock<Result<RelationshipsPart, Error>>>,
155    /// The names of the entries left out because an earlier entry has an equivalent name.
156    equivalent: Vec<String>,
157    /// Cumulative decompressed bytes across distinct parts inflated so far.
158    inflated_total: Arc<AtomicU64>,
159    /// The limits that the package was opened with.
160    limits: Limits,
161}
162
163impl fmt::Debug for Package {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.debug_struct("Package")
166            .field("parts", &self.parts.len())
167            .field("limits", &self.limits)
168            .finish_non_exhaustive()
169    }
170}
171
172/// One indexed part: its normalized name, ZIP central-directory metadata, and lazy byte cache.
173struct Part {
174    name: String,
175    zip_index: usize,
176    compressed_size: u64,
177    uncompressed_size: u64,
178    counted: AtomicBool,
179    data: OnceLock<Result<Vec<u8>, Error>>,
180}
181
182impl Clone for Part {
183    fn clone(&self) -> Self {
184        Self {
185            name: self.name.clone(),
186            zip_index: self.zip_index,
187            compressed_size: self.compressed_size,
188            uncompressed_size: self.uncompressed_size,
189            counted: AtomicBool::new(self.counted.load(Ordering::Relaxed)),
190            data: self.data.clone(),
191        }
192    }
193}
194
195impl Package {
196    /// Indexes a package from in-memory bytes without eagerly decompressing its parts.
197    ///
198    /// # Errors
199    ///
200    /// Returns an error when the ZIP central directory is unreadable or breaks a limit.
201    pub fn open(bytes: &[u8], limits: &Limits) -> Result<Self, Error> {
202        Self::open_shared(Arc::<[u8]>::from(bytes), limits)
203    }
204
205    /// Indexes a package from a shared byte buffer without copying or eagerly decompressing it.
206    ///
207    /// # Errors
208    ///
209    /// Returns an error when the ZIP central directory is unreadable or breaks a limit.
210    pub fn open_shared(bytes: Arc<[u8]>, limits: &Limits) -> Result<Self, Error> {
211        Self::open_backing(Arc::new(Backing::Memory(bytes)), limits)
212    }
213
214    /// Indexes a package from a caller-provided random-access byte source (such as browser
215    /// `File.slice()` or OPFS `FileSystemSyncAccessHandle`) without copying the archive into RAM.
216    ///
217    /// # Errors
218    ///
219    /// Returns an error when the ZIP central directory is unreadable or breaks a limit.
220    pub fn open_source(source: Arc<dyn RandomAccessRead>, limits: &Limits) -> Result<Self, Error> {
221        Self::open_backing(Arc::new(Backing::Custom(source)), limits)
222    }
223
224    /// Indexes a package directly from a native file on disk without loading the file into RAM.
225    ///
226    /// Parts are read and decompressed lazily via random-access file I/O when requested.
227    ///
228    /// # Errors
229    ///
230    /// Returns an error when the file cannot be opened, its ZIP central directory is unreadable,
231    /// or it breaks a limit.
232    #[cfg(not(target_arch = "wasm32"))]
233    pub fn open_file(path: &Path, limits: &Limits) -> Result<Self, Error> {
234        let file = std::fs::File::open(path).map_err(|_| Error::Zip(ZipFault::Archive))?;
235        let len = file
236            .metadata()
237            .map_err(|_| Error::Zip(ZipFault::Archive))?
238            .len();
239        Self::open_backing(
240            Arc::new(Backing::File {
241                file: Mutex::new(file),
242                len,
243            }),
244            limits,
245        )
246    }
247
248    /// Indexes the ZIP central directory of `backing` without inflating any entries.
249    fn open_backing(backing: Arc<Backing>, limits: &Limits) -> Result<Self, Error> {
250        let mut archive = zip::ZipArchive::new(BackingReader::new(backing))
251            .map_err(|_| Error::Zip(ZipFault::Archive))?;
252        if archive.len() > limits.max_entries {
253            return Err(Error::Limit(Limit::Entries));
254        }
255        let mut parts = BTreeMap::new();
256        let mut equivalent = Vec::new();
257        let mut declared_total = 0_u64;
258        for index in 0..archive.len() {
259            let file = archive
260                .by_index_raw(index)
261                .map_err(|_| Error::Zip(ZipFault::Entry))?;
262            if file.is_dir() {
263                continue;
264            }
265            let uncompressed_size = file.size();
266            let compressed_size = file.compressed_size();
267            check_entry(uncompressed_size, compressed_size, limits)?;
268            declared_total = declared_total.saturating_add(uncompressed_size);
269            if declared_total > limits.max_total_size {
270                return Err(Error::Limit(Limit::TotalSize));
271            }
272            let name = normalize(&file.name().map_err(|_| Error::Zip(ZipFault::Name))?);
273            match parts.entry(key(&name)) {
274                Entry::Occupied(_) => equivalent.push(name),
275                Entry::Vacant(slot) => {
276                    slot.insert(Part {
277                        name,
278                        zip_index: index,
279                        compressed_size,
280                        uncompressed_size,
281                        counted: AtomicBool::new(false),
282                        data: OnceLock::new(),
283                    });
284                }
285            }
286        }
287        let relationships = parts
288            .keys()
289            .filter(|name| in_relationships_folder(name))
290            .map(|name| (name.clone(), OnceLock::new()))
291            .collect();
292        Ok(Self {
293            archive: Arc::new(Mutex::new(Some(archive))),
294            parts,
295            relationships,
296            equivalent,
297            inflated_total: Arc::new(AtomicU64::new(0)),
298            limits: *limits,
299        })
300    }
301
302    /// Returns the limits that the package was opened with, which every reader of its parts
303    /// keeps to.
304    #[must_use]
305    pub const fn limits(&self) -> &Limits {
306        &self.limits
307    }
308
309    /// Returns the bytes of a part, decompressing and caching it on its first access. The name
310    /// may start with `/`, and its ASCII letters may differ in case from the part's name in the
311    /// package (ECMA-376 Part 2, 6.2.2.3).
312    ///
313    /// For large one-shot parts such as embedded media, prefer [`Package::read_part`] so the
314    /// inflated bytes are not pinned inside the package cache.
315    #[must_use]
316    pub fn part(&self, name: &str) -> Option<&[u8]> {
317        let part = self.parts.get(&key(name))?;
318        part.data
319            .get_or_init(|| self.inflate_part(part))
320            .as_deref()
321            .ok()
322    }
323
324    /// Reads and returns the bytes of a part on demand without pinning them in the package cache.
325    /// Returns `Ok(None)` when the package holds no such part. If the part was already cached by
326    /// [`Package::part`], returns a copy of the cached bytes.
327    ///
328    /// # Errors
329    ///
330    /// Returns an error if the entry cannot be decompressed or its actual inflated size breaks
331    /// [`Limits`].
332    pub fn read_part(&self, name: &str) -> Result<Option<Vec<u8>>, Error> {
333        let Some(part) = self.parts.get(&key(name)) else {
334            return Ok(None);
335        };
336        if let Some(cached) = part.data.get() {
337            return cached.clone().map(Some);
338        }
339        self.inflate_part(part).map(Some)
340    }
341
342    /// Reads and returns up to `max_bytes` leading bytes of a part on demand without inflating
343    /// the remainder of the entry or pinning bytes in the package cache. Returns `Ok(None)` when
344    /// the package holds no such part.
345    ///
346    /// Useful for sniffing image formats and parsing image headers (PNG IHDR, JPEG SOF, GIF, BMP)
347    /// without decompressing multi-megabyte media entries during layout.
348    ///
349    /// # Errors
350    ///
351    /// Returns an error if the ZIP entry cannot be opened or read.
352    pub fn read_part_prefix(&self, name: &str, max_bytes: usize) -> Result<Option<Vec<u8>>, Error> {
353        let Some(part) = self.parts.get(&key(name)) else {
354            return Ok(None);
355        };
356        if let Some(cached) = part.data.get() {
357            return cached
358                .as_ref()
359                .map(|bytes| {
360                    Some(
361                        bytes
362                            .get(..bytes.len().min(max_bytes))
363                            .unwrap_or(bytes)
364                            .to_vec(),
365                    )
366                })
367                .map_err(Clone::clone);
368        }
369        let limit = u64::try_from(max_bytes)
370            .unwrap_or(u64::MAX)
371            .min(self.limits.max_part_size);
372        let mut guard = self
373            .archive
374            .lock()
375            .map_err(|_| Error::Zip(ZipFault::Read))?;
376        let archive = guard.as_mut().ok_or(Error::Zip(ZipFault::Archive))?;
377        let mut file = archive
378            .by_index(part.zip_index)
379            .map_err(|_| Error::Zip(ZipFault::Entry))?;
380        let capacity = usize::try_from(part.uncompressed_size.min(limit)).unwrap_or(0);
381        let mut data = Vec::with_capacity(capacity);
382        (&mut file)
383            .take(limit)
384            .read_to_end(&mut data)
385            .map_err(|_| Error::Zip(ZipFault::Read))?;
386        Ok(Some(data))
387    }
388
389    /// Returns the declared uncompressed size in bytes of `name` from the ZIP central directory,
390    /// without decompressing the part.
391    #[must_use]
392    pub fn part_size(&self, name: &str) -> Option<u64> {
393        self.parts
394            .get(&key(name))
395            .map(|part| part.uncompressed_size)
396    }
397
398    /// Inflates `part` from the backing ZIP archive while enforcing actual size, ratio, and
399    /// cumulative total limits.
400    fn inflate_part(&self, part: &Part) -> Result<Vec<u8>, Error> {
401        let mut guard = self
402            .archive
403            .lock()
404            .map_err(|_| Error::Zip(ZipFault::Read))?;
405        let archive = guard.as_mut().ok_or(Error::Zip(ZipFault::Archive))?;
406        let mut file = archive
407            .by_index(part.zip_index)
408            .map_err(|_| Error::Zip(ZipFault::Entry))?;
409        let capacity =
410            usize::try_from(part.uncompressed_size.min(self.limits.max_part_size)).unwrap_or(0);
411        let mut data = Vec::with_capacity(capacity);
412        (&mut file)
413            .take(self.limits.max_part_size.saturating_add(1))
414            .read_to_end(&mut data)
415            .map_err(|_| Error::Zip(ZipFault::Read))?;
416        drop(file);
417        drop(guard);
418
419        let actual_size = data.len() as u64;
420        if actual_size > self.limits.max_part_size {
421            return Err(Error::Limit(Limit::PartSize));
422        }
423        check_entry(actual_size, part.compressed_size, &self.limits)?;
424        if !part.counted.swap(true, Ordering::Relaxed) {
425            let previous = self
426                .inflated_total
427                .fetch_add(actual_size, Ordering::Relaxed);
428            if previous.saturating_add(actual_size) > self.limits.max_total_size {
429                return Err(Error::Limit(Limit::TotalSize));
430            }
431        }
432        Ok(data)
433    }
434
435    /// Returns the name under which the package holds the part `name`, which [`Package::part`]
436    /// finds: as the package writes it, without a leading `/`. `None` when it holds no such
437    /// part.
438    #[must_use]
439    pub fn part_name(&self, name: &str) -> Option<&str> {
440        self.parts.get(&key(name)).map(|part| part.name.as_str())
441    }
442
443    /// Returns the names of all parts as the package writes them, without a leading `/`.
444    pub fn part_names(&self) -> impl Iterator<Item = &str> {
445        self.parts.values().map(|part| part.name.as_str())
446    }
447
448    /// Returns the names of the entries that the package leaves out, because an earlier entry
449    /// of the ZIP file has a name that differs from theirs only in ASCII case. The package
450    /// format forbids two such parts (ECMA-376 Part 2, 6.2.2.3); the package keeps the first.
451    pub fn equivalent_entries(&self) -> impl Iterator<Item = &str> {
452        self.equivalent.iter().map(String::as_str)
453    }
454
455    /// Returns the relationships part of a part, or of the package when `source` is empty: none
456    /// when the package has no such part. The package reads a relationships part on its first
457    /// use and keeps what it read.
458    ///
459    /// # Errors
460    ///
461    /// Returns an error when the relationships part cannot be read or is not valid XML.
462    pub fn relationships(&self, source: &str) -> Result<&RelationshipsPart, Error> {
463        let source = normalize(source);
464        let name = key(&relationships_part(&source));
465        let (Some(read), Some(part)) = (self.relationships.get(&name), self.parts.get(&name))
466        else {
467            return Ok(&NO_RELATIONSHIPS);
468        };
469        read.get_or_init(|| {
470            let data = part
471                .data
472                .get_or_init(|| self.inflate_part(part))
473                .as_ref()
474                .map_err(Error::clone)?;
475            read_relationships(&part.name, data, &source, &self.limits.xml)
476        })
477        .as_ref()
478        .map_err(Error::clone)
479    }
480
481    /// Returns the name of the main document part, such as `word/document.xml`.
482    ///
483    /// # Errors
484    ///
485    /// Returns an error when the package relationships are invalid or name no main document.
486    pub fn main_document(&self) -> Result<String, Error> {
487        Relationship::by_type(&self.relationships("")?.relationships, "/officeDocument")
488            .map(|rel| rel.target.clone())
489            .ok_or(Error::NoMainDocument)
490    }
491}
492
493/// The relationships part `part_name` (`data`) of `source`, parsed within `limits`.
494fn read_relationships(
495    part_name: &str,
496    data: &[u8],
497    source: &str,
498    limits: &XmlLimits,
499) -> Result<RelationshipsPart, Error> {
500    let doc = Document::parse(data, limits).map_err(Error::Xml)?;
501    let root = doc.root().map_err(Error::Xml)?;
502    let relationships = doc
503        .child_elements(root)
504        .filter(|id| doc.is(*id, RELATIONSHIPS_NS, "Relationship"))
505        .map(|id| {
506            let attr = |name| doc.attribute(id, None, name).unwrap_or("").to_owned();
507            let external = attr("TargetMode") == "External";
508            let target = attr("Target");
509            Relationship {
510                id: attr("Id"),
511                rel_type: attr("Type"),
512                target: if external {
513                    target
514                } else {
515                    resolve(source, &target)
516                },
517                external,
518            }
519        })
520        .collect();
521    Ok(RelationshipsPart {
522        name: part_name.to_owned(),
523        relationships,
524        undeclared_prefixes: doc.undeclared_prefixes().to_vec(),
525    })
526}
527
528fn check_entry(size: u64, compressed: u64, limits: &Limits) -> Result<(), Error> {
529    if size > limits.max_part_size {
530        return Err(Error::Limit(Limit::PartSize));
531    }
532    if size > 1 << 20 && size / compressed.max(1) > limits.max_ratio {
533        return Err(Error::Limit(Limit::Ratio));
534    }
535    Ok(())
536}
537
538fn normalize(name: &str) -> String {
539    name.trim_start_matches('/').to_owned()
540}
541
542/// The name by which the package finds a part: without a leading `/`, with the ASCII letters
543/// in lower case, since part names are equivalent under ASCII case-insensitive matching
544/// (ECMA-376 Part 2, 6.2.2.3 and 3.3.11).
545fn key(name: &str) -> String {
546    normalize(name).to_ascii_lowercase()
547}
548
549/// Whether a part lies in a `_rels` folder, where `relationships_part` puts every relationships
550/// part.
551fn in_relationships_folder(name: &str) -> bool {
552    name.starts_with("_rels/") || name.contains("/_rels/")
553}
554
555/// The name of the relationships part of the part `source`, or of the package when `source` is
556/// empty (ECMA-376 Part 2, 9.3.4): `word/_rels/document.xml.rels` for `word/document.xml`.
557#[must_use]
558pub fn relationships_part(source: &str) -> String {
559    match source.rsplit_once('/') {
560        Some((dir, file)) => format!("{dir}/_rels/{file}.rels"),
561        None if source.is_empty() => "_rels/.rels".to_owned(),
562        None => format!("_rels/{source}.rels"),
563    }
564}
565
566fn resolve(source: &str, target: &str) -> String {
567    if let Some(absolute) = target.strip_prefix('/') {
568        return absolute.to_owned();
569    }
570    let mut segments: Vec<&str> = match source.rsplit_once('/') {
571        Some((dir, _)) => dir.split('/').collect(),
572        None => Vec::new(),
573    };
574    for segment in target.split('/') {
575        match segment {
576            ".." => {
577                segments.pop();
578            }
579            "." | "" => {}
580            other => segments.push(other),
581        }
582    }
583    segments.join("/")
584}
585
586#[cfg(test)]
587mod tests {
588    use super::{
589        Error, Limit, Limits, Package, Relationship, RelationshipsPart, ZipFault, check_entry,
590        relationships_part, resolve,
591    };
592    use std::io::{Cursor, Write};
593    use zip::write::SimpleFileOptions;
594
595    const ROOT_RELS: &str = r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#;
596    const DOC_RELS: &str = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="t/styles" Target="styles.xml"/><Relationship Id="rId2" Type="t/link" Target="https://example.com" TargetMode="External"/><Relationship Id="rId3" Type="t/x" Target="../custom/x.xml"/></Relationships>"#;
597
598    fn package(files: &[(&str, &str)]) -> Vec<u8> {
599        let mut out = zip::ZipWriter::new(Cursor::new(Vec::new()));
600        out.add_directory("word/", SimpleFileOptions::default())
601            .unwrap();
602        for (name, body) in files {
603            out.start_file(*name, SimpleFileOptions::default()).unwrap();
604            out.write_all(body.as_bytes()).unwrap();
605        }
606        out.finish().unwrap().into_inner()
607    }
608
609    fn sample() -> Package {
610        let bytes = package(&[
611            ("_rels/.rels", ROOT_RELS),
612            ("word/document.xml", "<w/>"),
613            ("word/_rels/document.xml.rels", DOC_RELS),
614        ]);
615        Package::open(&bytes, &Limits::default()).unwrap()
616    }
617
618    #[test]
619    fn finds_parts() {
620        let pkg = sample();
621        assert_eq!(pkg.main_document().unwrap(), "word/document.xml");
622        assert_eq!(pkg.part("/word/document.xml"), Some(&b"<w/>"[..]));
623        assert_eq!(pkg.part_names().count(), 3);
624    }
625
626    #[test]
627    fn finds_relationships() {
628        let pkg = sample();
629        let read = pkg.relationships("word/document.xml").unwrap();
630        assert_eq!(read.name, "word/_rels/document.xml.rels");
631        assert_eq!(read.undeclared_prefixes, [] as [&str; 0]);
632        let rels = &read.relationships;
633        assert_eq!(rels[0].target, "word/styles.xml");
634        assert!(rels[1].external);
635        assert_eq!(rels[1].target, "https://example.com");
636        assert_eq!(rels[2].target, "custom/x.xml");
637        let none = pkg.relationships("word/styles.xml").unwrap();
638        assert_eq!(*none, RelationshipsPart::default());
639    }
640
641    #[test]
642    fn lists_the_undeclared_prefixes_of_a_relationships_part_without_their_relationships() {
643        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="a" Type="t/styles" Target="styles.xml"/><x:Relationship Id="b" Type="t/image" Target="media/b.png"/></Relationships>"#;
644        let pkg = Package::open(
645            &package(&[("word/_rels/document.xml.rels", rels)]),
646            &Limits::default(),
647        )
648        .unwrap();
649        let read = pkg.relationships("word/document.xml").unwrap();
650        assert_eq!(read.undeclared_prefixes, ["x"]);
651        let ids: Vec<&str> = read
652            .relationships
653            .iter()
654            .map(|rel| rel.id.as_str())
655            .collect();
656        assert_eq!(ids, ["a"]);
657    }
658
659    #[test]
660    fn finds_parts_and_relationships_whose_names_differ_in_ascii_case() {
661        let rels = r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="t/image" Target="media/IMAGE1.png"/></Relationships>"#;
662        let pkg = Package::open(
663            &package(&[
664                ("_rels/.rels", ROOT_RELS),
665                ("word/Document.xml", "<w/>"),
666                ("word/_rels/Document.XML.rels", rels),
667                ("Word/Media/image1.png", "png"),
668            ]),
669            &Limits::default(),
670        )
671        .unwrap();
672        let main = pkg.main_document().unwrap();
673        assert_eq!(main, "word/document.xml");
674        assert_eq!(pkg.part(&main), Some(&b"<w/>"[..]));
675        let read = pkg.relationships(&main).unwrap();
676        assert_eq!(read.name, "word/_rels/Document.XML.rels");
677        let rels = &read.relationships;
678        assert_eq!(rels[0].target, "word/media/IMAGE1.png");
679        assert_eq!(pkg.part(&rels[0].target), Some(&b"png"[..]));
680        let mut names: Vec<&str> = pkg.part_names().collect();
681        names.sort_unstable();
682        assert_eq!(
683            names,
684            [
685                "Word/Media/image1.png",
686                "_rels/.rels",
687                "word/Document.xml",
688                "word/_rels/Document.XML.rels"
689            ]
690        );
691        assert_eq!(pkg.equivalent_entries().count(), 0);
692    }
693
694    #[test]
695    fn keeps_the_first_of_two_entries_whose_names_differ_only_in_ascii_case() {
696        let pkg = Package::open(
697            &package(&[
698                ("a/b.xml", "first"),
699                ("A/B.xml", "second"),
700                ("a/c.xml", "c"),
701            ]),
702            &Limits::default(),
703        )
704        .unwrap();
705        assert_eq!(pkg.part("A/b.XML"), Some(&b"first"[..]));
706        assert_eq!(pkg.part_names().count(), 2);
707        assert_eq!(pkg.equivalent_entries().collect::<Vec<_>>(), ["A/B.xml"]);
708    }
709
710    #[test]
711    fn reads_a_relationships_part_once_and_keeps_what_it_read() {
712        let pkg = sample();
713        let first = pkg.relationships("/word/document.xml").unwrap();
714        let again = pkg.relationships("word/document.xml").unwrap();
715        assert_eq!(first.relationships.len(), 3);
716        assert!(std::ptr::eq(first, again));
717        let bad = Package::open(
718            &package(&[("word/_rels/document.xml.rels", "<a>")]),
719            &Limits::default(),
720        )
721        .unwrap();
722        let error = bad.relationships("word/document.xml").unwrap_err();
723        assert!(matches!(error, Error::Xml(_)));
724        assert_eq!(bad.relationships("word/document.xml").unwrap_err(), error);
725    }
726
727    #[test]
728    fn looks_up_the_first_relationship_to_a_part_by_id_or_by_type() {
729        let rel = |id: &str, rel_type: &str, target: &str, external| Relationship {
730            id: id.to_owned(),
731            rel_type: rel_type.to_owned(),
732            target: target.to_owned(),
733            external,
734        };
735        let rels = [
736            rel("rId1", "t/styles", "https://example.com", true),
737            rel(
738                "rId1",
739                "http://purl.oclc.org/ooxml/officeDocument/relationships/styles",
740                "word/strict.xml",
741                false,
742            ),
743            rel(
744                "rId2",
745                "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles",
746                "word/transitional.xml",
747                false,
748            ),
749            rel("rId3", "t/link", "https://example.com", true),
750        ];
751        let target = |rel: Option<&Relationship>| rel.map(|rel| rel.target.clone());
752        assert_eq!(
753            target(Relationship::by_id(&rels, "rId1")),
754            Some("word/strict.xml".to_owned())
755        );
756        assert_eq!(
757            target(Relationship::by_id(&rels, "rId2")),
758            Some("word/transitional.xml".to_owned())
759        );
760        assert_eq!(Relationship::by_id(&rels, "rId3"), None);
761        assert_eq!(Relationship::by_id(&rels, "rId4"), None);
762        assert_eq!(
763            target(Relationship::by_type(&rels, "/styles")),
764            Some("word/strict.xml".to_owned())
765        );
766        assert_eq!(Relationship::by_type(&rels, "/link"), None);
767        assert_eq!(Relationship::by_type(&rels, "/numbering"), None);
768    }
769
770    #[test]
771    fn reports_a_missing_main_document_and_bad_zip() {
772        let pkg = Package::open(&package(&[("a.xml", "<a/>")]), &Limits::default()).unwrap();
773        assert_eq!(pkg.main_document().unwrap_err(), Error::NoMainDocument);
774        assert_eq!(
775            Package::open(b"not a zip", &Limits::default()).unwrap_err(),
776            Error::Zip(ZipFault::Archive)
777        );
778        let bad = Package::open(&package(&[("_rels/.rels", "<a>")]), &Limits::default()).unwrap();
779        assert!(matches!(bad.main_document(), Err(Error::Xml(_))));
780    }
781
782    #[test]
783    fn enforces_limits() {
784        let bytes = package(&[("a.xml", "0123456789"), ("b.xml", "0123456789")]);
785        let small_part = Limits {
786            max_part_size: 5,
787            ..Limits::default()
788        };
789        assert_eq!(
790            Package::open(&bytes, &small_part).unwrap_err(),
791            Error::Limit(Limit::PartSize)
792        );
793        let small_total = Limits {
794            max_total_size: 15,
795            ..Limits::default()
796        };
797        assert_eq!(
798            Package::open(&bytes, &small_total).unwrap_err(),
799            Error::Limit(Limit::TotalSize)
800        );
801        let few = Limits {
802            max_entries: 2,
803            ..Limits::default()
804        };
805        assert_eq!(
806            Package::open(&bytes, &few).unwrap_err(),
807            Error::Limit(Limit::Entries)
808        );
809        assert_eq!(
810            check_entry(2 << 20, 1, &Limits::default()),
811            Err(Error::Limit(Limit::Ratio))
812        );
813        assert_eq!(check_entry(2 << 20, 1 << 20, &Limits::default()), Ok(()));
814    }
815
816    #[test]
817    fn resolves_names() {
818        assert_eq!(relationships_part(""), "_rels/.rels");
819        assert_eq!(relationships_part("a.xml"), "_rels/a.xml.rels");
820        assert_eq!(
821            relationships_part("word/document.xml"),
822            "word/_rels/document.xml.rels"
823        );
824        assert_eq!(resolve("word/document.xml", "/media/a.png"), "media/a.png");
825        assert_eq!(
826            resolve("word/document.xml", "./media/a.png"),
827            "word/media/a.png"
828        );
829        assert_eq!(resolve("", "word/document.xml"), "word/document.xml");
830    }
831
832    #[test]
833    fn errors_display() {
834        let cases = [
835            (
836                Error::Zip(ZipFault::Archive),
837                "unreadable ZIP package: its central directory does not read",
838            ),
839            (
840                Error::Zip(ZipFault::Entry),
841                "unreadable ZIP package: an entry of its central directory does not read",
842            ),
843            (
844                Error::Zip(ZipFault::Name),
845                "unreadable ZIP package: the name of an entry does not read",
846            ),
847            (
848                Error::Zip(ZipFault::Read),
849                "unreadable ZIP package: the data of an entry does not read",
850            ),
851            (
852                Error::Limit(Limit::Entries),
853                "package breaks the limit on the number of entries",
854            ),
855            (
856                Error::Limit(Limit::PartSize),
857                "package breaks the limit on the size of a part",
858            ),
859            (
860                Error::Limit(Limit::TotalSize),
861                "package breaks the limit on the total size",
862            ),
863            (
864                Error::Limit(Limit::Ratio),
865                "package breaks the limit on the compression ratio",
866            ),
867            (Error::NoMainDocument, "package has no main document"),
868        ];
869        for (error, message) in cases {
870            assert_eq!(error.to_string(), message);
871            assert!(std::error::Error::source(&error).is_none());
872        }
873        let xml = Error::Xml(f_office_xml::Error::DocType);
874        assert_eq!(xml.to_string(), "bad relationships part");
875        let cause = std::error::Error::source(&xml).map(ToString::to_string);
876        assert_eq!(cause.as_deref(), Some("XML with a DOCTYPE is not allowed"));
877    }
878
879    #[test]
880    fn reads_parts_lazily_without_caching_read_part() {
881        let bytes = package(&[
882            ("word/document.xml", "<doc/>"),
883            ("word/media/large.bin", "0123456789abcdef"),
884        ]);
885        let pkg = Package::open(&bytes, &Limits::default()).unwrap();
886        assert_eq!(pkg.part_size("word/media/large.bin"), Some(16));
887        assert!(pkg.parts["word/media/large.bin"].data.get().is_none());
888        let media = pkg.read_part("word/media/large.bin").unwrap();
889        assert_eq!(media.as_deref(), Some(&b"0123456789abcdef"[..]));
890        // `read_part` does not pin large media in the package cache.
891        assert!(pkg.parts["word/media/large.bin"].data.get().is_none());
892        // `part` lazily populates the cache on demand.
893        assert_eq!(pkg.part("word/document.xml"), Some(&b"<doc/>"[..]));
894        assert!(pkg.parts["word/document.xml"].data.get().is_some());
895    }
896
897    #[cfg(not(target_arch = "wasm32"))]
898    #[test]
899    fn opens_a_package_lazily_from_a_file_and_enforces_mobile_limits() {
900        let bytes = package(&[
901            (
902                "_rels/.rels",
903                r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
904            ),
905            ("word/document.xml", "<w:document/>"),
906        ]);
907        let path = std::env::temp_dir().join(format!(
908            "f-office-opc-lazy-{}-{}.docx",
909            std::process::id(),
910            bytes.len()
911        ));
912        std::fs::write(&path, &bytes).unwrap();
913        let pkg = Package::open_file(&path, &Limits::mobile()).unwrap();
914        assert_eq!(pkg.main_document().unwrap(), "word/document.xml");
915        assert_eq!(
916            pkg.read_part("word/document.xml").unwrap().as_deref(),
917            Some(&b"<w:document/>"[..])
918        );
919        assert_eq!(pkg.limits().max_total_size, 128 << 20);
920        let _ = std::fs::remove_file(&path);
921    }
922}