archive#
bounded ZIP32 containers (stored and DEFLATE) -- crate root lib/archive/lib.rs
In-memory ZIP interchange (ZIP32, ZIP64 when it is needed). New native library code,
independent of document/UI code. Raw DEFLATE, inflate and CRC come from jflib-compress
primitives; no paths are extracted. `opc` builds the Open Packaging Conventions on top;
`cfb` reads compound files ("OLE", [MS-CFB]), the container of Office's binary formats.
ZipFs shows an archive as a read-only plat::vfs tree:
plat::vfs::mount("pack", Arc::new(archive::ZipFs::new(&bytes, Limits::default())?))
-> plat::read_file("pack://textures/a.png"), plat::File::open("pack://..", FO_READ),
plat::fs::stat (size; mtime: the entry's DOS time, read as UTC)
archive crate root#
struct EntryOne decoded archive part with a normalized, relative UTF-8 name.name: Stringdata: Vec<u8>
struct LimitsBounds are checked before decompression or allocation of advertised sizes. The default (512 parts, 8 MiB a part, 32 MiB in all, archives up to 32 MiB) suits documents; readers of large packages pass larger values and a smallerratio:Limits { entries: 100_000, part_bytes: 512 << 20, total_bytes: 2 << 30, archive_bytes: 1 << 30, ratio: 200 }.entries: usize-- Most parts in one archive.part_bytes: usize-- Most bytes of one part, uncompressed.total_bytes: usize-- Most bytes of all parts together, uncompressed.archive_bytes: usize-- Most bytes of the archive itself.ratio: usize-- Highest ratio of a DEFLATE part's size to its compressed size, checked for parts over 1 MiB before they are inflated: a denser part is refused withLimit(a ZIP bomb). The default, 1032, is the most DEFLATE can reach and so refuses nothing; a part claiming more isInvalidwhatever this value is.
enum ErrorStructural, integrity, feature or resource-limit failure.InvalidUnsupportedChecksumLimit
enum MethodHowwrite_withstores the parts.Stored-- Uncompressed, aswritestores them.Deflate(u8)-- DEFLATE at a level from 1 (fastest) to 9 (smallest); 6 is the usual choice, 0 counts as 1 and higher values as 9. A part that does not get smaller, or that would get denser than the writer'sLimits::ratio, is stored instead.
fn read(b: &[u8], limits: Limits) -> Result<Vec<Entry>, Error>Read stored/DEFLATE ZIP files, ZIP64 included. Reject encryption, multi-disk archives, ambiguous names (absolute,..,\,:,%, control characters, a case-insensitive duplicate), duplicate parts, overlapping local records, data between or after the parts, sizes a DEFLATE stream cannot reach and CRC mismatches.fn write(entries: &[Entry], limits: Limits) -> Result<Vec<u8>, Error>Deterministic stored ZIP writer (UTF-8 names, fixed DOS date 1980-01-01): the same parts always give the same bytes. ZIP64 records only where an archive needs them (65535 parts or more, a size or offset of 4 GiB or more).fn write_with(entries: &[Entry], limits: Limits, method: Method) -> Result<Vec<u8>, Error>writewith DEFLATE whenmethodasks for it; just as deterministic. A part DEFLATE would not make smaller, or would pack pastlimits.ratio(a reader with the same limits would refuse it), is stored.fn write_zip64_from(entries: &[Entry], limits: Limits, method: Method, at: u64) -> Result<Vec<u8>, Error>For tests:write_withthat writes ZIP64 records for every size and offset fromatbytes on, as ifatwere 4 GiB.struct ZipFs(plat::vfs::MemFs)A ZIP archive as a read-only plat::vfs provider (mount it under a scheme of its own). The parts are checked and decompressed once, withinlimits.
impl ZipFs
fn new(b: &[u8], limits: Limits) -> Result<ZipFs, Error>Read every part of the archive; Invalid also for names that collide as file and folder.
archive/cfb.rs#
Source: lib/archive/cfb.rs
Compound files ("OLE", "structured storage") as Microsoft's open specification [MS-CFB]
describes them: a file system of storages and streams inside one file, the container of
Office's binary formats (Visio's .vss/.vsd, Word's .doc, Outlook's .msg, the VBA project of
a macro document). New native library code from the specification; read only.
cfb::File::read(&bytes, cfb::Limits::default())? -> the directory, checked
file.entries() / file.children(i) / file.find(&["VisioDocument"]) -> entries by path
file.stream(i)? -> the bytes of a stream
Every file is untrusted input. Everything the header and the directory claim is checked
before it is believed: the file's and each stream's size against Limits, every sector
number against the file, each chain of sectors walked at most once around (a loop is
Invalid, never a hang), the directory's tree of siblings without cycles and with every entry
at most once, names as the specification allows them. Nothing is ever written.
/// The first eight bytes of every compound file.
SIGNATURE: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]
struct LimitsBounds of a compound file, checked before anything is allocated. The default (64 MiB a file and a stream, 4096 directory entries) suits documents.file_bytes: usize-- Most bytes of the file itself.stream_bytes: usize-- Most bytes of one stream.entries: usize-- Most directory entries (storages, streams and unused slots together).
enum KindWhat a directory entry is.Root-- The root storage (entry 0); its stream is the mini stream.Storage-- A storage: a directory of further entries.Stream-- A stream of bytes.
struct EntryOne storage or stream of the directory.name: String-- The name (at most 31 UTF-16 code units, without "/", "\", ":" and "!").kind: Kindclsid: [u8; 16]-- The class id of a storage (zeros for a stream).size: u64-- The size of a stream in bytes.
struct File<'a>A compound file read into memory: its directory and the tables to find a stream's bytes.fn sniff(bytes: &[u8]) -> boolWhetherbytesstart like a compound file (only the signature is looked at).
impl<'a> File<'a>
fn read(bytes: &'a [u8], limits: Limits) -> Result<File<'a>, Error>Read the header, the allocation tables and the directory of a compound file, version 3 (512-byte sectors) or 4 (4096-byte sectors). Refused withInvalid: a wrong signature, byte order or sector size, a sector number outside the file, a chain that loops or ends early, a directory tree with a cycle, an entry reached twice or a malformed name;Unsupported: another major version;Limit: the file, a stream or the directory overlimits.fn entries(&self) -> &[Entry]All directory entries; index 0 is the root. Unused slots and entries no storage reaches have an empty name and are nobody's child.fn children(&self, index: usize) -> &[usize]The children of the storage atindex(the root is 0), in the directory's order.fn find(&self, path: &[&str]) -> Option<usize>The entry at a path of names from the root (&["VisioDocument"],&["Macros", "VBA", "dir"]); names compare as the specification says, upper case against upper case.fn stream(&self, index: usize) -> Result<Vec<u8>, Error>The bytes of the stream atindex:Invalidfor a storage or a chain that is too short,Limitfor a stream overLimits::stream_bytes.
archive/opc.rs#
Source: lib/archive/opc.rs
Open Packaging Conventions (ECMA-376 Part 2) over this crate's ZIP reader and writer: a
package's parts, their content types ([Content_Types].xml) and relationships (_rels/*.rels).
DOCX (doc_io) and VSDX (diagram_io) share it. New native library code, taken out of doc_io's
DOCX preservation. Nothing outside the package is ever resolved or fetched: external targets
stay text.
Package::read(bytes, limits, rules) -> parts, content types, relationships, all checked
package.relationships(source) / package.resolve(source, target) / package.part(name)
package.set_part(..) / remove_part(..) / set_relationships(..), then package.write(..):
the parts nobody touched go back as they came (unknown parts are kept, never dropped)
Part names are compared the way OPC says, ASCII case-insensitive and percent-escape aware
("Word/Media/a%20b.png" names the same part as "word/media/a b.png"), unless Rules::exact_names
asks for the older profile of exact strings without escapes.
/// The ZIP item that holds the content types; it is no part of its own.
CONTENT_TYPES: &str = "[Content_Types].xml"
/// The package's own relationship part.
PACKAGE_RELS: &str = "_rels/.rels"
/// Content type of a relationship part.
RELS_TYPE: &str = "application/vnd.openxmlformats-package.relationships+xml"
/// Namespace of `[Content_Types].xml`.
NS_TYPES: &str = "http://schemas.openxmlformats.org/package/2006/content-t ...
/// Namespace of relationship parts.
NS_RELS: &str = "http://schemas.openxmlformats.org/package/2006/relations ...
/// Relationship type from the package to its main part (transitional OOXML).
OFFICE_DOCUMENT: &str = "http://schemas.openxmlformats.org/officeDocument/2006/re ...
/// Relationship type from the package to its main part (strict OOXML).
OFFICE_DOCUMENT_STRICT: &str = "http://purl.oclc.org/ooxml/officeDocument/relationships/ ...
enum ErrorWhy a package was refused.Zip(crate::Error)-- The ZIP container.Xml(xml::Error)--[Content_Types].xmlor a relationship part is not XML withinRules::xml.Invalid-- Package structure: a missing or duplicate part, content type or relationship id, a part without a content type, a relationship part without its source, a target that leaves the package or names no part, text that is not Unicode.Root(String)--[Content_Types].xmlor a relationship part has another root element, or attributes or text on it; the root's local name.Address-- A part name or internal target this module does not resolve: empty, a backslash,:,?,#, a control character or a bad percent-escape (also an escaped/or\); withRules::exact_namesany%.ContentType-- An empty content type, or withoutRules::macrosone of a macro project.MacroPart-- WithoutRules::macros: a part of a macro project (vbaProject.bin,vbaData.xml), whatever its content type says.MacroRelationship-- WithoutRules::macros: a relationship of a macro project's type.
struct RulesWhat a package may hold and how its names compare.macros: bool-- Accept macro (VBA) projects. Off by default: content types, relationship types and part names of a macro project refuse the package.exact_names: bool-- Compare part names and targets as exact strings and refuse percent-escapes, instead of OPC's case-insensitive, escape-aware equivalence (and refuse%in ZIP names). The conservative profile of jfWord's DOCX reader.xml: xml::Limits-- Limits of[Content_Types].xmland of each relationship part.
impl Rules
const DEFAULT: Rules = Rules { macros: false, exact_names: false, xml: xml::Limi ...No macros, OPC's name equivalence, the XML reader's default limits.fn resolve(&self, source: &str, target: &str) -> Result<String, Error>Resolve a relationship's target against its source part (""for the package) to a part name without the leading/...may not climb out of the package. With OPC's equivalence the result is in canonical form (seenormalize).fn normalize(name: &str) -> Result<String, Error>A part name in canonical form, without the leading/: escapes of unreserved characters decoded (%41isA), other escapes in upper case, spaces, non-ASCII and other characters a URI path may not hold escaped (äis%C3%A4).Addressfor a bad name: a bad escape, an escaped/or\, a control character, an empty,.or..segment.fn same_part(a: &str, b: &str) -> boolWhether two part names name the same part (OPC: ASCII case-insensitive, afternormalize).fn rels_name(source: &str) -> StringThe relationship part of a source part:_rels/.relsfor the package (""),dir/_rels/name.relsfordir/name.fn rels_source(name: &str) -> Result<String, Error>The source part of a relationship part (""for_rels/.rels);Invalidfor a name that is no relationship part's.struct ContentTypes[Content_Types].xml: content types by extension (defaults) and by part (overrides).
impl ContentTypes
fn new() -> SelfEmpty: no defaults, no overrides, OPC's name equivalence.fn get(&self, part: &str) -> Option<&str>The content type of a part: its override, else the default for its extension (case-insensitive); None when it has neither.fn defaults(&self) -> impl Iterator<Item = (&str, &str)>The defaults in file order: (extension, content type).fn overrides(&self) -> impl Iterator<Item = (&str, &str)>The overrides in file order: (part name without the leading/, content type).fn set_default(&mut self, extension: &str, content_type: &str) -> Result<(), Error>Set the default of an extension (no.,/or\), replacing an earlier one.fn set_override(&mut self, part: &str, content_type: &str) -> Result<(), Error>Set the override of a part, replacing an earlier one.fn remove_override(&mut self, part: &str) -> boolRemove the override of a part; false when it had none.fn to_xml(&self) -> Result<String, Error>[Content_Types].xmlwith an XML declaration: the defaults, then the overrides.struct RelationshipOne relationship of a source part.id: String-- Unique among the source's relationships (rId1…).kind: String-- The relationship type, a URI (Type).target: String-- The target as written: relative to the source part, or a URI whenexternal.external: bool--TargetMode="External": the target is outside the package and never followed here.
fn parse_relationships(xml: &[u8], rules: Rules) -> Result<Vec<Relationship>, Error>The relationships of one relationship part, checked but not resolved: the root element, each relationship's attributes, unique ids, the target mode, macro types.fn relationships_xml(list: &[Relationship]) -> Result<String, Error>A relationship part with an XML declaration.struct PackageAn OPC package: every ZIP item in archive order with its bytes, the content types and the main part. Parts this crate does not understand are kept as they are;writeputs them back unchanged,[Content_Types].xmltoo unless the content types changed.
impl Package
fn new(rules: Rules) -> PackageAn empty package to fill: only[Content_Types].xml.writeneeds the package's relationships (set_relationships("", ..)) and a content type for every part.fn read(bytes: &[u8], limits: Limits, rules: Rules) -> Result<Package, Error>Read and check a package within the ZIPlimits(percent-escapes in ZIP names only withoutRules::exact_names).fn from_entries(entries: Vec<Entry>, rules: Rules) -> Result<Package, Error>Check the ZIP items of a package already read.fn entries(&self) -> &[Entry]Every ZIP item in archive order,[Content_Types].xmlincluded as it was read (or last written); parts added later at the end.fn rules(&self) -> RulesThe rules the package was read with.fn main_part(&self) -> Option<&str>The stored name of the part the package's internalofficeDocumentrelationship names (its main part,word/document.xmlorvisio/document.xml).fn content_types(&self) -> &ContentTypesThe content types.fn content_types_mut(&mut self) -> &mut ContentTypesThe content types to change;writechecks the result.fn content_type(&self, name: &str) -> Option<&str>The content type of a part.fn name_of(&self, name: &str) -> Option<&str>The stored name of the part a name refers to.fn part(&self, name: &str) -> Option<&[u8]>The bytes of a part (any equivalent name finds it).fn relationships(&self, source: &str) -> Result<Vec<Relationship>, Error>The relationships of a part (""for the package's own); empty when it has none.fn resolve(&self, source: &str, target: &str) -> Result<&str, Error>The stored name of the part an internal target ofsourcenames.fn set_part(&mut self, name: &str, content_type: &str, data: Vec<u8>) -> Result<(), Error>Add a part or replace its bytes (an existing part keeps its stored name), and makecontent_typeits content type: the default of its extension when that matches, otherwise an override.fn replace(&mut self, name: &str, data: Vec<u8>) -> Result<(), Error>Replace the bytes of an existing part, keeping its content type.fn remove_part(&mut self, name: &str) -> boolRemove a part with its override and its own relationship part; false when there is no such part. Relationships of other parts that name it are the caller's to change.fn set_relationships(&mut self, source: &str, list: &[Relationship]) -> Result<(), Error>Replace the relationships of a part ("": the package's); an empty list removes its relationship part. Adds the default for.relswhen there is none.fn write(&self, limits: Limits, method: Method) -> Result<Vec<u8>, Error>The package as a ZIP archive, after checking it asreadwould: every part in its order,[Content_Types].xmlnew when the content types changed. Deterministic: the same package always gives the same bytes.