Skip to main content

rust_motion_affinity/
container.rs

1//! The Affinity archive: header, the chain of file allocation tables (one per save) and
2//! bounded, CRC-checked extraction of named entries such as `doc.dat` and raster tiles.
3
4use std::collections::{HashMap, HashSet};
5use std::io::Read;
6
7use crate::Error;
8
9pub const MAGIC: &[u8; 4] = b"\x00\xffKA";
10/// Oldest and newest container versions seen in real documents (Affinity 1.x writes 8,
11/// Affinity 3 writes 12). Version 7 is described by afread but no sample exists.
12pub const VERSIONS: std::ops::RangeInclusive<u16> = 8..=12;
13/// `Prsn` (stored byte-reversed): documents. Asset, brush and style libraries share the magic.
14const DOCUMENT_KIND: &[u8; 4] = b"nsrP";
15
16/// A save appends one table; real files have one to a few hundred.
17const MAX_TABLES: usize = 4096;
18/// zstd window ceiling: real documents use a few MiB; this stops a header from reserving gigabytes.
19const MAX_ZSTD_WINDOW: u64 = 64 << 20;
20
21/// Decompression budget for one import. Every entry declares its size, which is checked against
22/// these limits before anything is allocated, and the decoded length must match it exactly.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Limits {
25    /// Largest single entry (`doc.dat` or one tile).
26    pub max_entry: usize,
27    /// Total bytes extracted over the whole import.
28    pub max_total: usize,
29    /// Bytes of decoded pixels one import may hold: every layer's RGBA together, plus the
30    /// temporary planes the layer being read decodes through. The entry limits bound what is
31    /// extracted, not what the layers materialized out of it cost (#4960).
32    pub max_pixel_bytes: usize,
33}
34
35impl Default for Limits {
36    fn default() -> Self {
37        // The gigabyte the other importers allow decoded pixels (`io`'s `MAX_PIXEL_BYTES`).
38        Self {
39            max_entry: 256 << 20,
40            max_total: 1 << 30,
41            max_pixel_bytes: 1 << 30,
42        }
43    }
44}
45
46/// The container header, all integers little-endian.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub struct Header {
49    pub version: u16,
50    /// Seen as 0, 4 or 8 in real files; bits 0 and 1 mark container variants that are rejected.
51    pub flags: u16,
52    pub(crate) fat_offset: u64,
53    pub(crate) thumbnail_offset: u64,
54    /// Save time in Unix seconds, as written by the application.
55    pub saved: u32,
56}
57
58/// One FAT record, as of the newest table that mentions its id.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct Entry {
61    pub id: u32,
62    pub name: String,
63    offset: u64,
64    size: u64,
65    compressed: u64,
66    crc: u32,
67    compression: u8,
68}
69
70impl Entry {
71    /// Decompressed size declared by the table.
72    pub fn size(&self) -> u64 {
73        self.size
74    }
75}
76
77#[derive(Debug)]
78pub struct Archive<'a> {
79    bytes: &'a [u8],
80    pub header: Header,
81    /// Head revision of every named, non-deleted entry.
82    entries: HashMap<String, Entry>,
83    /// Number of tables (saves) in the chain.
84    pub revisions: usize,
85    extracted: usize,
86    limits: Limits,
87}
88
89pub(crate) struct Cursor<'a> {
90    bytes: &'a [u8],
91    pub(crate) pos: usize,
92}
93
94impl<'a> Cursor<'a> {
95    pub(crate) fn new(bytes: &'a [u8], pos: usize) -> Self {
96        Self { bytes, pos }
97    }
98    pub(crate) fn remaining(&self) -> usize {
99        self.bytes.len().saturating_sub(self.pos)
100    }
101    pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8], Error> {
102        let end = self
103            .pos
104            .checked_add(n)
105            .ok_or(Error::Malformed("length overflow"))?;
106        let s = self
107            .bytes
108            .get(self.pos..end)
109            .ok_or(Error::Malformed("truncated data"))?;
110        self.pos = end;
111        Ok(s)
112    }
113    pub(crate) fn array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
114        let s = self.take(N)?;
115        let mut a = [0u8; N];
116        a.copy_from_slice(s);
117        Ok(a)
118    }
119    pub(crate) fn u8(&mut self) -> Result<u8, Error> {
120        Ok(self.array::<1>()?[0])
121    }
122    pub(crate) fn u16(&mut self) -> Result<u16, Error> {
123        Ok(u16::from_le_bytes(self.array()?))
124    }
125    pub(crate) fn u32(&mut self) -> Result<u32, Error> {
126        Ok(u32::from_le_bytes(self.array()?))
127    }
128    pub(crate) fn u64(&mut self) -> Result<u64, Error> {
129        Ok(u64::from_le_bytes(self.array()?))
130    }
131}
132
133fn offset(v: u64) -> Result<usize, Error> {
134    usize::try_from(v).map_err(|_| Error::Malformed("offset beyond addressable memory"))
135}
136
137/// True when `bytes` start with the Affinity container signature (documents and libraries).
138pub fn is_affinity(bytes: &[u8]) -> bool {
139    bytes.starts_with(MAGIC)
140}
141
142/// Check the signature, version and document kind.
143pub fn header(bytes: &[u8]) -> Result<Header, Error> {
144    if !is_affinity(bytes) {
145        return Err(Error::Malformed("missing container signature"));
146    }
147    let mut c = Cursor::new(bytes, 4);
148    let version = c.u16()?;
149    let flags = c.u16()?;
150    if !VERSIONS.contains(&version) {
151        return Err(Error::Unsupported("unknown container version"));
152    }
153    if flags & 3 != 0 {
154        return Err(Error::Unsupported("container variant"));
155    }
156    if c.take(4)? != DOCUMENT_KIND {
157        return Err(Error::Unsupported(
158            "this Affinity file is a library (assets, brushes or styles), not a document",
159        ));
160    }
161    if c.take(4)? != b"#Inf" {
162        return Err(Error::Malformed("missing information header"));
163    }
164    let fat_offset = c.u64()?;
165    let thumbnail_offset = c.u64()?;
166    c.take(16)?;
167    let saved = u32::try_from(c.u64()?).unwrap_or(0);
168    c.take(8)?;
169    if c.take(4)? != b"Prot" {
170        return Err(Error::Malformed("missing protocol header"));
171    }
172    Ok(Header {
173        version,
174        flags,
175        fat_offset,
176        thumbnail_offset,
177        saved,
178    })
179}
180
181impl<'a> Archive<'a> {
182    pub fn open(bytes: &'a [u8], limits: Limits) -> Result<Self, Error> {
183        let header = header(bytes)?;
184        // Newest record per id: (table date, table index, record).
185        let mut latest: HashMap<u32, (u64, usize, Option<Entry>)> = HashMap::new();
186        let mut names: HashMap<u32, String> = HashMap::new();
187        let mut seen = HashSet::new();
188        let mut next = header.fat_offset;
189        let mut tables = 0usize;
190        while next != 0 {
191            if !seen.insert(next) {
192                return Err(Error::Malformed("allocation tables form a cycle"));
193            }
194            tables += 1;
195            if tables > MAX_TABLES {
196                return Err(Error::Limit("too many saved revisions"));
197            }
198            let mut c = Cursor::new(bytes, offset(next)?);
199            let tag = c.array::<4>()?;
200            let level = match &tag {
201                b"#FAT" => 1,
202                b"#FT2" => 2,
203                b"#FT3" => 3,
204                b"#FT4" => 4,
205                _ => return Err(Error::Malformed("missing allocation table")),
206            };
207            next = c.u64()?;
208            let date = c.u64()?;
209            c.take(24)?;
210            let files = c.u32()?;
211            c.take(8)?;
212            let dirs = c.u16()?;
213            c.take(1)?;
214            for _ in 0..files {
215                let id = c.u32()?;
216                let flag = c.u8()?;
217                let mut record = None;
218                match flag {
219                    0 | 1 => {
220                        let offset = c.u64()?;
221                        let size = c.u64()?;
222                        let compressed = c.u64()?;
223                        let crc = c.u32()?;
224                        let stored = c.u8()?;
225                        if level >= 2 {
226                            c.take(4)?;
227                        }
228                        if level >= 4 {
229                            c.take(4)?;
230                        }
231                        // Old tables number the methods; newer ones store the method byte itself.
232                        let compression = if level <= 2 {
233                            match stored {
234                                1 => 0x01,
235                                2 => 0x41,
236                                3 => 0x81,
237                                4 => 0xC1,
238                                _ => 0,
239                            }
240                        } else {
241                            stored
242                        };
243                        record = Some(Entry {
244                            id,
245                            name: String::new(),
246                            offset,
247                            size,
248                            compressed,
249                            crc,
250                            compression,
251                        });
252                    }
253                    2 => {}
254                    _ => return Err(Error::Malformed("unknown allocation record")),
255                }
256                if flag == 0 {
257                    let len = usize::from(c.u16()?);
258                    let name = String::from_utf8_lossy(c.take(len)?).into_owned();
259                    names.entry(id).or_insert(name);
260                }
261                // Equal dates: the first table in the chain (the newest) wins, as in afread.
262                let replace = latest.get(&id).is_none_or(|(d, _, _)| date > *d);
263                if replace {
264                    latest.insert(id, (date, tables, record));
265                }
266            }
267            for _ in 0..dirs {
268                let len = usize::from(c.u16()?);
269                c.take(10)?;
270                c.take(len)?;
271            }
272        }
273        let mut entries = HashMap::new();
274        for (id, (_, _, record)) in latest {
275            if let (Some(mut e), Some(name)) = (record, names.get(&id)) {
276                e.name = name.clone();
277                entries.insert(e.name.clone(), e);
278            }
279        }
280        Ok(Self {
281            bytes,
282            header,
283            entries,
284            revisions: tables,
285            extracted: 0,
286            limits,
287        })
288    }
289
290    pub fn entry(&self, name: &str) -> Option<&Entry> {
291        self.entries.get(name)
292    }
293
294    pub fn entry_names(&self) -> impl Iterator<Item = &str> {
295        self.entries.keys().map(String::as_str)
296    }
297
298    /// Bytes extracted so far, counted against [`Limits::max_total`].
299    pub fn extracted(&self) -> usize {
300        self.extracted
301    }
302
303    /// Extract an entry by name: decompress, undo the byte predictor and verify the CRC.
304    pub fn read(&mut self, name: &str) -> Result<Vec<u8>, Error> {
305        let e = self
306            .entries
307            .get(name)
308            .ok_or(Error::Malformed("missing archive entry"))?
309            .clone();
310        let size = usize::try_from(e.size).map_err(|_| Error::Limit("archive entry too large"))?;
311        if size > self.limits.max_entry {
312            return Err(Error::Limit("archive entry too large"));
313        }
314        let total = self
315            .extracted
316            .checked_add(size)
317            .ok_or(Error::Limit("document too large"))?;
318        if total > self.limits.max_total {
319            return Err(Error::Limit("document too large"));
320        }
321        let mut c = Cursor::new(self.bytes, offset(e.offset)?);
322        if c.take(4)? != b"#Fil" {
323            return Err(Error::Malformed("archive entry has no data block"));
324        }
325        let method = e.compression & 3;
326        let stored_len = if matches!(method, 1 | 2) {
327            e.compressed
328        } else {
329            e.size
330        };
331        let data = c.take(offset(stored_len)?)?;
332        let mut out = match method {
333            1 => inflate(data, size)?,
334            2 => unzstd(data, size)?,
335            _ => data.to_vec(),
336        };
337        if out.len() != size {
338            return Err(Error::Malformed("archive entry size mismatch"));
339        }
340        unpredict(&mut out, e.compression)?;
341        if crc32fast::hash(&out) != e.crc {
342            return Err(Error::Malformed("archive entry checksum mismatch"));
343        }
344        self.extracted = total;
345        Ok(out)
346    }
347}
348
349/// Read at most `size + 1` bytes so a stream that decodes past its declared size is caught
350/// without unbounded allocation.
351fn read_bounded(mut r: impl Read, size: usize) -> Result<Vec<u8>, Error> {
352    let mut out = Vec::with_capacity(size.min(64 << 20));
353    let cap = u64::try_from(size).unwrap_or(u64::MAX).saturating_add(1);
354    r.by_ref()
355        .take(cap)
356        .read_to_end(&mut out)
357        .map_err(|_| Error::Malformed("corrupt compressed entry"))?;
358    Ok(out)
359}
360
361fn inflate(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
362    read_bounded(flate2::read::ZlibDecoder::new(data), size)
363}
364
365fn unzstd(data: &[u8], size: usize) -> Result<Vec<u8>, Error> {
366    let mut src = data;
367    let mut out = Vec::new();
368    // Entries may hold several concatenated frames.
369    while !src.is_empty() {
370        let left = size
371            .checked_sub(out.len())
372            .ok_or(Error::Malformed("archive entry size mismatch"))?;
373        let decoder =
374            ruzstd::decoding::StreamingDecoder::new_with_max_window_size(&mut src, MAX_ZSTD_WINDOW)
375                .map_err(|_| Error::Malformed("corrupt compressed entry"))?;
376        let frame = read_bounded(decoder, left)?;
377        if frame.is_empty() {
378            return Err(Error::Malformed("corrupt compressed entry"));
379        }
380        out.extend_from_slice(&frame);
381        if out.len() > size {
382            return Err(Error::Malformed("archive entry size mismatch"));
383        }
384    }
385    Ok(out)
386}
387
388/// Undo the byte predictor selected by the high bits of the compression byte.
389fn unpredict(b: &mut [u8], compression: u8) -> Result<(), Error> {
390    match (compression & 0xC0, compression & 0x20 != 0) {
391        (0x00, _) => {}
392        (0x40, _) => byte_delta(b),
393        (0x80, false) => {
394            let mut prev = 0u16;
395            for pair in b.as_chunks_mut::<2>().0.iter_mut() {
396                let v = u16::from_le_bytes(*pair).wrapping_add(prev);
397                *pair = v.to_le_bytes();
398                prev = v;
399            }
400        }
401        (0x80, true) => {
402            byte_delta(b);
403            // A 64 KiB tile of 16-bit samples is stored as all high bytes, then all low bytes.
404            if b.len() == 0x10000 {
405                let planes = b.to_vec();
406                let (hi, lo) = planes.split_at(0x8000);
407                for (i, out) in b.as_chunks_mut::<4>().0.iter_mut().enumerate() {
408                    let (Some(h), Some(l)) = (hi.get(2 * i..2 * i + 2), lo.get(2 * i..2 * i + 2))
409                    else {
410                        return Err(Error::Malformed("tile size"));
411                    };
412                    *out = [l[0], h[0], l[1], h[1]];
413                }
414            }
415        }
416        _ => return Err(Error::Unsupported("archive entry predictor")),
417    }
418    Ok(())
419}
420
421fn byte_delta(b: &mut [u8]) {
422    let mut prev = 0u8;
423    for v in b {
424        *v = v.wrapping_add(prev);
425        prev = *v;
426    }
427}