Skip to main content

xisf_core/
reader.rs

1//! Opening a monolithic XISF file and getting data blocks out of it.
2
3use alloc::borrow::Cow;
4use std::path::{Path, PathBuf};
5
6use base64::Engine as _;
7
8use crate::block::{Checksum, ChecksumAlgorithm, HEADER_DIR_TOKEN, Location, TextEncoding};
9use crate::codec;
10use crate::err;
11use crate::error::Result;
12use crate::header::{self, DataRef, Header};
13use crate::layout::{self, Layout};
14
15/// How a caller fetches a `url(...)` block. See
16/// [`Reader::set_url_resolver`].
17pub type UrlResolver = Box<dyn Fn(&str) -> Result<Vec<u8>> + Send + Sync>;
18
19/// Whether a block's stored bytes matched its recorded checksum.
20#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21pub enum ChecksumStatus {
22    /// The element records no checksum. The spec makes it optional, so this
23    /// is not a failure.
24    Absent,
25    Valid,
26    Invalid,
27}
28
29impl ChecksumStatus {
30    pub fn is_failure(self) -> bool {
31        self == ChecksumStatus::Invalid
32    }
33}
34
35/// Where a reader's bytes come from.
36enum Source {
37    /// Absent under Miri, which cannot execute `mmap`: `Reader::open` reads
38    /// the file whole there, so nothing would construct this and `dead_code`
39    /// would fire.
40    #[cfg(not(miri))]
41    Mapped(memmap2::Mmap),
42    Owned(Vec<u8>),
43}
44
45impl core::ops::Deref for Source {
46    type Target = [u8];
47    fn deref(&self) -> &[u8] {
48        match self {
49            #[cfg(not(miri))]
50            Source::Mapped(m) => m,
51            Source::Owned(v) => v,
52        }
53    }
54}
55
56impl core::fmt::Debug for Source {
57    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58        let kind = match self {
59            #[cfg(not(miri))]
60            Source::Mapped(_) => "Mapped",
61            Source::Owned(_) => "Owned",
62        };
63        write!(f, "{kind}({} bytes)", self.len())
64    }
65}
66
67/// An open XISF file.
68pub struct Reader {
69    source: Source,
70    layout: Layout,
71    header: Header,
72    /// See [`Reader::follow_absolute_paths`].
73    allow_absolute_paths: bool,
74    /// See [`Reader::set_url_resolver`].
75    url_resolver: Option<UrlResolver>,
76    /// See [`Reader::set_verify_checksums`]. On unless a caller turns it off.
77    verify_checksums: bool,
78    /// Where the file came from, so a `path:` block can be resolved relative
79    /// to it, as the spec requires.
80    path: Option<PathBuf>,
81}
82
83impl core::fmt::Debug for Reader {
84    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
85        f.debug_struct("Reader")
86            .field("source", &self.source)
87            .field("path", &self.path)
88            .field("images", &self.header.images().len())
89            .field("url_resolver", &self.url_resolver.is_some())
90            .finish_non_exhaustive()
91    }
92}
93
94impl Reader {
95    /// Open and scan a file from disk.
96    ///
97    /// The file is memory-mapped, so an attached block costs nothing until it
98    /// is read.
99    ///
100    /// # Mapped files and concurrent modification
101    ///
102    /// Because the file stays mapped for as long as the reader lives, another
103    /// process that *truncates* it out from under us turns a later block read
104    /// into `SIGBUS`, which no amount of checking in this crate can catch:
105    /// the bytes were valid when they were checked and stopped existing
106    /// afterwards. This is inherent to memory mapping rather than specific to
107    /// this crate, and it is the reason [`Reader::from_bytes`] exists -- a
108    /// caller reading files that others may be rewriting should read the
109    /// bytes themselves and hand them over, which costs a copy and removes
110    /// the hazard entirely.
111    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
112        let path = path.as_ref();
113
114        // Miri interprets rather than executes, so it has no `mmap`. Reading
115        // the file whole is observably the same to every caller -- `Source`
116        // hands out a `&[u8]` either way -- and it is what lets this crate be
117        // checked under Miri at all.
118        #[cfg(miri)]
119        {
120            let bytes = std::fs::read(path)?;
121            let (layout, header) = Self::scan(&bytes)?;
122            return Ok(Self {
123                source: Source::Owned(bytes),
124                layout,
125                header,
126                path: Some(path.into()),
127                allow_absolute_paths: false,
128                verify_checksums: true,
129                url_resolver: None,
130            });
131        }
132
133        #[cfg(not(miri))]
134        {
135            let file = std::fs::File::open(path)?;
136
137            // SAFETY: mapping is unsafe because another process truncating
138            // the file turns a later read into SIGBUS. That hazard is
139            // inherent to memory mapping; XISF files are written whole rather
140            // than modified in place, and mapping is what lets a
141            // multi-gigabyte image be read without loading it all.
142            let mapped = unsafe { memmap2::Mmap::map(&file) }?;
143            let (layout, header) = Self::scan(&mapped)?;
144            Ok(Self {
145                source: Source::Mapped(mapped),
146                layout,
147                header,
148                path: Some(path.into()),
149                allow_absolute_paths: false,
150                verify_checksums: true,
151                url_resolver: None,
152            })
153        }
154    }
155
156    /// Scan a file already in memory.
157    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
158        let (layout, header) = Self::scan(&bytes)?;
159        Ok(Self {
160            source: Source::Owned(bytes),
161            layout,
162            header,
163            path: None,
164            allow_absolute_paths: false,
165            verify_checksums: true,
166            url_resolver: None,
167        })
168    }
169
170    fn scan(bytes: &[u8]) -> Result<(Layout, Header)> {
171        let layout = layout::scan(bytes)?;
172        let header = header::parse(layout::header_str(bytes, &layout)?)?;
173        Ok((layout, header))
174    }
175
176    pub fn header(&self) -> &Header {
177        &self.header
178    }
179
180    /// The header's XML source, exactly as the file holds it.
181    ///
182    /// The parsed [`Header`] is what a reader normally wants, but a tool that
183    /// shows a file to a person needs the text: the parse is lossy about
184    /// formatting, attribute order and comments, so re-serialising it would
185    /// show something the file does not contain.
186    pub fn header_text(&self) -> Result<&str> {
187        layout::header_str(&self.source, &self.layout)
188    }
189
190    pub fn bytes(&self) -> &[u8] {
191        &self.source
192    }
193
194    pub fn path(&self) -> Option<&Path> {
195        self.path.as_deref()
196    }
197
198    /// The stored bytes of an element's data block, before decompression.
199    ///
200    /// An attached block is borrowed straight from the mapping; a text-encoded
201    /// one has to be decoded, so it is owned.
202    pub fn stored_block(&self, data: &DataRef) -> Result<Cow<'_, [u8]>> {
203        let stored = self.stored_block_unchecked(data)?;
204
205        // A file that records a checksum is telling the reader how to know
206        // whether these bytes are the bytes that were written. Handing them
207        // over without looking, when the file itself said how to check, is a
208        // silent corruption the format went out of its way to make
209        // detectable -- so the check is on unless a caller turns it off.
210        if self.verify_checksums
211            && let Some(checksum) = &data.checksum
212            && digest(&stored, checksum.algorithm)? != checksum.digest
213        {
214            return Err(err!(
215                ChecksumMismatch,
216                "the block's {} checksum does not match its contents",
217                checksum.algorithm.name()
218            ));
219        }
220        Ok(stored)
221    }
222
223    /// The stored bytes without checking the recorded checksum.
224    ///
225    /// This is what [`Reader::verify`] reads, since it reports a mismatch
226    /// rather than failing on one.
227    fn stored_block_unchecked(&self, data: &DataRef) -> Result<Cow<'_, [u8]>> {
228        let location = data
229            .location
230            .as_ref()
231            .ok_or_else(|| err!(NotFound, "this element has no data block"))?;
232
233        match location {
234            Location::Attachment { position, size } => {
235                let start = usize::try_from(*position)
236                    .map_err(|_| err!(Unsupported, "block position is beyond this platform"))?;
237                let len = usize::try_from(*size)
238                    .map_err(|_| err!(Unsupported, "block size is beyond this platform"))?;
239                let end = start
240                    .checked_add(len)
241                    .ok_or_else(|| err!(Truncated, "block position + size overflows"))?;
242
243                // A `location` is caller-controlled addressing, so both ends
244                // are checked before any slicing happens.
245                if start < self.layout.data_start() {
246                    return Err(err!(
247                        BadAttribute,
248                        "a block at {start} would overlap the header, which ends at {}",
249                        self.layout.data_start()
250                    ));
251                }
252                if end > self.source.len() {
253                    return Err(err!(
254                        Truncated,
255                        "a block of {len} bytes at {start} runs {} past the end of the file",
256                        end - self.source.len()
257                    ));
258                }
259                Ok(Cow::Borrowed(&self.source[start..end]))
260            }
261
262            Location::Inline { encoding } => {
263                // Revision 1 serializes an empty vector or matrix as an inline
264                // block with empty character data -- "the only data blocks of
265                // zero length" -- so absent text is a block of no bytes, not a
266                // block that is missing. Refusing it made every empty
267                // aggregate property unreadable.
268                let text = data.text.as_deref().unwrap_or("");
269                Ok(Cow::Owned(decode_text(text, *encoding)?))
270            }
271            Location::Embedded { encoding } => {
272                // An embedded block with no `<Data>` content is empty rather
273                // than missing, for the same reason an inline one is.
274                let text = data.text.as_deref().unwrap_or("");
275                Ok(Cow::Owned(decode_text(text, *encoding)?))
276            }
277
278            // "External XISF data blocks shall not occur in a monolithic XISF
279            // file." The mirror rule -- no attached blocks in a distributed
280            // unit -- is enforced by the bounds check above, since a header
281            // file has no bytes after its header for one to live in.
282            //
283            // This is a substitution channel as much as a conformance rule: a
284            // monolithic file that quietly draws its pixels from a sibling on
285            // disk cannot be detected by its own checksum, which covers the
286            // substituted bytes.
287            Location::Path { .. } | Location::Url { .. }
288                if self.layout.form == crate::layout::Form::Monolithic =>
289            {
290                Err(err!(
291                    BadAttribute,
292                    "a monolithic XISF file may not reference an external data block; \
293                     external blocks belong to a distributed unit"
294                ))
295            }
296
297            Location::Path { path, index } => {
298                Ok(Cow::Owned(read_external_block(&self.resolve_relative(path)?, path, *index)?))
299            }
300            Location::Url { url, index } => {
301                let Some(fetch) = &self.url_resolver else {
302                    return Err(err!(
303                        Unsupported,
304                        "{url:?} is a remote block; install a resolver with \
305                         `set_url_resolver` to allow fetching"
306                    ));
307                };
308                let bytes = fetch(url)?;
309                Ok(Cow::Owned(extract_external(bytes, *index, url)?))
310            }
311        }
312    }
313
314    /// The usable bytes of a block: decoded, decompressed and unshuffled.
315    pub fn block(&self, data: &DataRef) -> Result<Cow<'_, [u8]>> {
316        let stored = self.stored_block(data)?;
317        match &data.compression {
318            None => Ok(stored),
319            Some(compression) => Ok(Cow::Owned(codec::decode(&stored, compression)?)),
320        }
321    }
322
323    /// Check a block's stored bytes against its recorded checksum.
324    ///
325    /// The checksum covers the block *as stored*, so a compressed block can be
326    /// verified without being decompressed.
327    pub fn verify(&self, data: &DataRef) -> Result<ChecksumStatus> {
328        let Some(checksum) = &data.checksum else {
329            return Ok(ChecksumStatus::Absent);
330        };
331        let stored = self.stored_block_unchecked(data)?;
332        Ok(if digest(&stored, checksum.algorithm)? == checksum.digest {
333            ChecksumStatus::Valid
334        } else {
335            ChecksumStatus::Invalid
336        })
337    }
338
339    /// Whether to check a block against its recorded checksum when reading it.
340    ///
341    /// On by default, because the specification requires a decoder to check a
342    /// digest the file went to the trouble of recording, and because handing
343    /// back corrupt bytes without a word is the worse failure.
344    ///
345    /// It costs one hash pass over the block: about 15 ms for a 32 MB frame
346    /// with sha-1 or sha-256, and about 55 ms with sha-512 -- roughly twice
347    /// what the typed read that usually follows it costs, and small against
348    /// the disk read that must precede it. See `docs/PERFORMANCE.md`.
349    ///
350    /// Turning it off is for a caller who reads the same block repeatedly, or
351    /// who has verified the file by other means; [`Reader::verify`] then
352    /// remains available on demand, reporting a mismatch rather than failing.
353    ///
354    /// Blocks with no recorded checksum are unaffected: the spec makes them
355    /// optional, and their absence is not a failure.
356    pub fn set_verify_checksums(&mut self, verify: bool) {
357        self.verify_checksums = verify;
358    }
359
360    /// Install a resolver for `url(...)` blocks.
361    ///
362    /// **This library never makes a network request itself, and that is a
363    /// deliberate design decision rather than an omission.**
364    ///
365    /// A `url(...)` locator is a request, written in a file, for the reader to
366    /// go and fetch something. Honouring it automatically would mean that
367    /// `Reader::open` on a local file could reach out to a host the caller
368    /// never named -- which is a server-side request forgery primitive when
369    /// the caller is a service, and reaches cloud metadata endpoints and
370    /// internal addresses that are not otherwise exposed. It would also make
371    /// timeouts, proxies, redirects and certificate trust this crate's
372    /// problem, and pull in an HTTP and TLS stack that the rest of the
373    /// workspace does without.
374    ///
375    /// Handing the decision to the caller solves all of it at once. The
376    /// resolver receives the URL exactly as the file wrote it and returns the
377    /// bytes, so a caller can allow only the schemes and hosts they mean to,
378    /// apply their own timeouts, or refuse. Without one, a remote block is an
379    /// `Unsupported` error that says so.
380    ///
381    /// ```no_run
382    /// # use xisf_core::Reader;
383    /// # fn main() -> xisf_core::Result<()> {
384    /// let mut reader = Reader::open("unit.xisf")?;
385    /// reader.set_url_resolver(|url| {
386    ///     if !url.starts_with("https://data.example.com/") {
387    ///         return Err(xisf_core::Error::new(
388    ///             xisf_core::ErrorKind::Unsupported,
389    ///             format!("refusing to fetch {url}"),
390    ///         ));
391    ///     }
392    ///     // ... fetch and return the bytes ...
393    ///     # unimplemented!()
394    /// });
395    /// # Ok(())
396    /// # }
397    /// ```
398    pub fn set_url_resolver(
399        &mut self,
400        resolver: impl Fn(&str) -> Result<Vec<u8>> + Send + Sync + 'static,
401    ) {
402        self.url_resolver = Some(Box::new(resolver));
403    }
404
405    /// Remove any installed resolver, so remote blocks are refused again.
406    pub fn clear_url_resolver(&mut self) {
407        self.url_resolver = None;
408    }
409
410    /// Whether to follow `path(...)` locators that name an absolute path.
411    ///
412    /// Off by default, and that is a deliberate departure from the letter of
413    /// the specification, which defines the field as an *absolute* path. A
414    /// header is untrusted input: a file that says
415    /// `location="path(/etc/shadow)"` is asking a library to read a file the
416    /// user never named, and returning its bytes as pixel data is an
417    /// arbitrary-file-read primitive dressed as an image decoder.
418    ///
419    /// Relative locators still resolve beside the referring file, which is
420    /// what a distributed unit actually needs and what the corpus uses. A
421    /// caller who genuinely wants absolute paths -- a trusted pipeline, say --
422    /// turns them on and takes that decision knowingly.
423    pub fn follow_absolute_paths(&mut self, allow: bool) {
424        self.allow_absolute_paths = allow;
425    }
426
427    /// Resolve a `path(...)` locator to a file to read.
428    ///
429    /// A relative locator is resolved beside the referring file and may not
430    /// climb out of its directory; an absolute one is refused unless
431    /// [`follow_absolute_paths`](Reader::follow_absolute_paths) says otherwise.
432    fn resolve_relative(&self, locator: &str) -> Result<PathBuf> {
433        // `@header_dir` is the specification's own spelling for "beside the
434        // file that named this", and it is the only relative form the
435        // grammar actually defines -- `path(@header_dir/blocks.xisb)`. It is
436        // stripped here rather than anywhere later so that everything after
437        // it, including the containment check below, sees an ordinary
438        // relative path and `@header_dir/../..` is refused like any other
439        // attempt to climb out.
440        if let Some(rest) = locator.strip_prefix(HEADER_DIR_TOKEN) {
441            let rest = rest.strip_prefix('/').unwrap_or(rest);
442            if rest.is_empty() {
443                return Err(err!(BadAttribute, "{locator:?} names a directory, not a file"));
444            }
445            return self.resolve_beside(rest);
446        }
447
448        let candidate = Path::new(locator);
449        if candidate.is_absolute() {
450            if !self.allow_absolute_paths {
451                return Err(err!(
452                    BadAttribute,
453                    "{locator:?} is an absolute path; following one from a file header is \
454                     refused unless the caller opts in"
455                ));
456            }
457            return Ok(candidate.to_path_buf());
458        }
459        self.resolve_beside(locator)
460    }
461
462    /// Resolve a locator relative to the referring file's own directory.
463    ///
464    /// A locator with no `@header_dir` prefix and no leading slash is
465    /// accepted here too. The grammar does not define that form -- a `path()`
466    /// is either absolute or `@header_dir`-prefixed -- but files written that
467    /// way exist, and reading one beside its header is what its author
468    /// plainly meant and is no more permissive than the documented form.
469    fn resolve_beside(&self, locator: &str) -> Result<PathBuf> {
470        let base = self.path.as_ref().and_then(|p| p.parent()).ok_or_else(|| {
471            err!(NotFound, "this file has no directory to resolve {locator:?} in")
472        })?;
473
474        let candidate = Path::new(locator);
475        if locator.contains("://") {
476            return Err(err!(BadAttribute, "{locator:?} is a URL, not a path"));
477        }
478        for component in candidate.components() {
479            use std::path::Component;
480            match component {
481                Component::Normal(_) | Component::CurDir => {}
482                _ => {
483                    return Err(err!(
484                        BadAttribute,
485                        "{locator:?} climbs out of the referring file's directory"
486                    ));
487                }
488            }
489        }
490        let joined = base.join(candidate);
491
492        // Checking the *components* is not enough. A locator with no `..` in
493        // it at all -- a plain `blocks.xisb` -- can be a symbolic link to
494        // anywhere, and following it reads a file the locator never named.
495        // Whoever supplies a malicious unit generally supplies the directory
496        // it unpacks into, so planting the link beside the header is exactly
497        // as easy as writing the header. Resolving both ends and checking
498        // containment is what actually holds.
499        let resolved = joined
500            .canonicalize()
501            .map_err(|e| err!(NotFound, "{locator:?} could not be resolved: {e}"))?;
502        let root = base
503            .canonicalize()
504            .map_err(|e| err!(NotFound, "the referring file's directory is unreadable: {e}"))?;
505        if !resolved.starts_with(&root) {
506            return Err(err!(
507                BadAttribute,
508                "{locator:?} resolves to {}, outside the referring file's directory",
509                resolved.display()
510            ));
511        }
512        Ok(resolved)
513    }
514}
515
516/// Read an external block file, refusing anything that is not a regular file.
517///
518/// A named pipe or a character device passes every path check and then never
519/// ends: reading `/dev/zero` exhausts memory, reading a fifo blocks forever.
520/// Neither is a data blocks file, and a decoder has no reason to open one.
521fn read_external_block(path: &Path, locator: &str, index: Option<u64>) -> Result<Vec<u8>> {
522    let metadata = std::fs::metadata(path)
523        .map_err(|e| err!(NotFound, "{locator:?} could not be read: {e}"))?;
524    if !metadata.is_file() {
525        return Err(err!(
526            BadAttribute,
527            "{locator:?} is not a regular file, so it is not a data block"
528        ));
529    }
530
531    // Which of the two shapes this is decides how much of it has to be read,
532    // so the signature is looked at before anything larger is committed to.
533    let mut file = std::fs::File::open(path).map_err(|e| err!(NotFound, "{locator:?}: {e}"))?;
534    let mut signature = [0u8; 8];
535    let is_blocks_file = match std::io::Read::read_exact(&mut file, &mut signature) {
536        Ok(()) => &signature == crate::distributed::BLOCKS_SIGNATURE,
537        // Too short to be a blocks file, so it can only be a plain resource.
538        Err(_) => false,
539    };
540
541    if !is_blocks_file {
542        if index.is_some() {
543            return Err(err!(
544                BadAttribute,
545                "{locator:?} names a block by identifier but is not an XISF data blocks file"
546            ));
547        }
548        // A plain external resource is its own block, so its whole contents
549        // are wanted and its size is not something to second-guess.
550        return Ok(std::fs::read(path)?);
551    }
552
553    let id = index.ok_or_else(|| {
554        err!(BadAttribute, "{locator:?} is a data blocks file, so the locator must name a block")
555    })?;
556    crate::distributed::read_block_from(&mut file, metadata.len(), id)?
557        .ok_or_else(|| err!(NotFound, "{locator:?} has no block with identifier {id}"))
558}
559
560/// Take one block out of an external file.
561///
562/// Two shapes are legal here and they are told apart by the file itself. An
563/// XISF *data blocks file* begins with `XISB0100` and holds an index naming
564/// each block by identifier; the locator's trailing number is that
565/// identifier, not an ordinal. Any other file is a plain external resource
566/// whose whole contents are the block.
567///
568/// Reading a blocks file as though it were plain would hand the caller the
569/// signature and index as though they were pixels, which is the sort of thing
570/// that produces an image of noise rather than an error.
571fn extract_external(bytes: Vec<u8>, index: Option<u64>, path: &str) -> Result<Vec<u8>> {
572    let is_blocks_file = bytes.len() >= crate::distributed::BLOCKS_SIGNATURE.len()
573        && &bytes[..8] == crate::distributed::BLOCKS_SIGNATURE;
574
575    if !is_blocks_file {
576        if index.is_some() {
577            return Err(err!(
578                BadAttribute,
579                "{path:?} names a block by identifier but is not an XISF data blocks file"
580            ));
581        }
582        return Ok(bytes);
583    }
584
585    let id = index.ok_or_else(|| {
586        err!(BadAttribute, "{path:?} is a data blocks file, so the locator must name a block")
587    })?;
588    let parsed = crate::distributed::parse_blocks_file(&bytes)?;
589    let element = parsed
590        .get(id)
591        .ok_or_else(|| err!(NotFound, "{path:?} has no block with identifier {id}"))?;
592    if element.is_free() {
593        return Err(err!(NotFound, "block {id} in {path:?} is a free placeholder with no data"));
594    }
595
596    let start = usize::try_from(element.position)
597        .map_err(|_| err!(Unsupported, "block {id} lies beyond this platform's range"))?;
598    let len = usize::try_from(element.length)
599        .map_err(|_| err!(Unsupported, "block {id} is too large for this platform"))?;
600    let end = start
601        .checked_add(len)
602        .ok_or_else(|| err!(Truncated, "block {id}'s position and length overflow"))?;
603    if end > bytes.len() {
604        return Err(err!(
605            Truncated,
606            "block {id} in {path:?} runs {} bytes past the end of the file",
607            end - bytes.len()
608        ));
609    }
610    Ok(bytes[start..end].to_vec())
611}
612
613/// Decode a text-encoded block. Whitespace is insignificant in both encodings.
614fn decode_text(text: &str, encoding: TextEncoding) -> Result<Vec<u8>> {
615    let compact: String = text.chars().filter(|c| !c.is_whitespace()).collect();
616    match encoding {
617        TextEncoding::Base64 => base64::engine::general_purpose::STANDARD
618            .decode(compact.as_bytes())
619            .map_err(|e| err!(BadAttribute, "base64: {e}")),
620        TextEncoding::Hex => {
621            if !compact.len().is_multiple_of(2) {
622                return Err(err!(BadAttribute, "hex data has an odd number of digits"));
623            }
624            // Decoded from bytes: slicing the string two bytes at a time
625            // assumed every character was one byte wide and panicked when one
626            // was not, which a header is free to contain.
627            crate::block::decode_hex(compact.as_bytes())
628                .ok_or_else(|| err!(BadAttribute, "hex data is not hexadecimal"))
629        }
630    }
631}
632
633/// Hash `bytes` with the algorithm named.
634///
635/// Every algorithm the format allows is always available. Revision 1 requires
636/// a conforming decoder to verify SHA-1, SHA-256 and SHA-512, and requires
637/// decoders to verify every block checksum they are given, so a build that
638/// could only report "not compiled in" would be a decoder that cannot claim
639/// conformance. The `Result` is kept because it is part of the public
640/// signature and because callers already handle it.
641pub fn digest(bytes: &[u8], algorithm: ChecksumAlgorithm) -> Result<Vec<u8>> {
642    use sha1::Digest as _;
643    Ok(match algorithm {
644        ChecksumAlgorithm::Sha1 => sha1::Sha1::digest(bytes).to_vec(),
645        ChecksumAlgorithm::Sha256 => sha2::Sha256::digest(bytes).to_vec(),
646        ChecksumAlgorithm::Sha512 => sha2::Sha512::digest(bytes).to_vec(),
647        // FIPS 202, not the original Keccak submission -- Revision 1 makes
648        // that explicit, and the two differ in their padding.
649        ChecksumAlgorithm::Sha3_256 => sha3::Sha3_256::digest(bytes).to_vec(),
650        ChecksumAlgorithm::Sha3_512 => sha3::Sha3_512::digest(bytes).to_vec(),
651    })
652}
653
654/// The hex spelling of a digest, as a `checksum` attribute carries it.
655pub fn digest_hex(digest: &[u8]) -> String {
656    digest.iter().map(|b| format!("{b:02x}")).collect()
657}
658
659/// Recompute a checksum attribute for `bytes`.
660pub fn checksum_of(bytes: &[u8], algorithm: ChecksumAlgorithm) -> Result<Checksum> {
661    Ok(Checksum { algorithm, digest: digest(bytes, algorithm)? })
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667    use crate::ErrorKind;
668
669    /// A distributed unit's header file: the XML alone, no signature and no
670    /// preamble. This is the form external data blocks belong to -- a
671    /// monolithic file may not reference one.
672    fn header_file(header: &str) -> Vec<u8> {
673        header.as_bytes().to_vec()
674    }
675
676    fn build(header: &str, trailing: &[u8]) -> Vec<u8> {
677        let mut out = Vec::new();
678        out.extend_from_slice(crate::layout::SIGNATURE);
679        out.extend_from_slice(&(header.len() as u32).to_le_bytes());
680        out.extend_from_slice(&[0; 4]);
681        out.extend_from_slice(header.as_bytes());
682        out.extend_from_slice(trailing);
683        out
684    }
685
686    #[test]
687    fn reads_an_inline_block() {
688        let xml = r#"<xisf version="1.0"><Image location="inline:base64">QUJD</Image></xisf>"#;
689        let reader = Reader::from_bytes(build(xml, &[])).unwrap();
690        let image = reader.header().images()[0];
691        assert_eq!(&*reader.block(&image.data).unwrap(), b"ABC");
692    }
693
694    #[test]
695    fn reads_a_hex_block_ignoring_whitespace() {
696        let xml = r#"<xisf version="1.0"><Image location="inline:hex">41 42
697        43</Image></xisf>"#;
698        let reader = Reader::from_bytes(build(xml, &[])).unwrap();
699        let image = reader.header().images()[0];
700        assert_eq!(&*reader.block(&image.data).unwrap(), b"ABC");
701    }
702
703    #[test]
704    fn reads_an_attached_block() {
705        // The offset is absolute in the file, so it has to clear the preamble
706        // and the header rather than being counted from the data.
707        const AT: usize = 256;
708        let xml = format!(r#"<xisf version="1.0"><Image location="attachment:{AT}:3"/></xisf>"#);
709        let padding = AT - (crate::layout::PREAMBLE_LEN + xml.len());
710        let mut trailing = vec![0u8; padding];
711        trailing.extend_from_slice(b"XYZ");
712
713        let reader = Reader::from_bytes(build(&xml, &trailing)).unwrap();
714        let image = reader.header().images()[0];
715        assert_eq!(&*reader.block(&image.data).unwrap(), b"XYZ");
716    }
717
718    /// A `location` is addressing the caller controls, so every way of
719    /// pointing it somewhere it should not go is refused rather than sliced.
720    #[test]
721    fn a_block_may_not_address_outside_the_file() {
722        for location in [
723            "attachment:0:10",                   // overlaps the header
724            "attachment:100000:1",               // past the end
725            "attachment:18446744073709551615:1", // overflows
726        ] {
727            let xml = format!(r#"<xisf version="1.0"><Image location="{location}"/></xisf>"#);
728            let reader = Reader::from_bytes(build(&xml, &[0; 32])).unwrap();
729            let image = reader.header().images()[0];
730            assert!(
731                reader.stored_block(&image.data).is_err(),
732                "{location} should have been refused"
733            );
734        }
735    }
736
737    /// A header is untrusted input, so neither climbing out of the referring
738    /// file's directory nor naming an absolute path is followed by default.
739    #[test]
740    fn external_paths_are_not_followed_where_they_should_not_be() {
741        for locator in ["path(../secret)", "path(/etc/passwd)", "path(a/../../b)"] {
742            let xml = format!(r#"<xisf version="1.0"><Image location="{locator}"/></xisf>"#);
743            let reader = Reader::from_bytes(build(&xml, &[])).unwrap();
744            let image = reader.header().images()[0];
745            let err = reader.stored_block(&image.data).unwrap_err();
746            assert!(
747                matches!(err.kind(), ErrorKind::NotFound | ErrorKind::BadAttribute),
748                "{locator} produced {err}"
749            );
750        }
751    }
752
753    /// Turning absolute paths on is a decision the caller makes knowingly.
754    #[test]
755    fn absolute_paths_are_followed_only_when_asked_for() {
756        let dir = std::env::temp_dir().join(format!("xisf-abs-{}", std::process::id()));
757        std::fs::create_dir_all(&dir).unwrap();
758        let target = dir.join("block.bin");
759        std::fs::write(&target, b"payload").unwrap();
760
761        let xml = format!(
762            r#"<xisf version="1.0"><Image location="path({})"/></xisf>"#,
763            target.display().to_string().replace('\\', "/")
764        );
765        let mut reader = Reader::from_bytes(header_file(&xml)).unwrap();
766
767        let data = reader.header().images()[0].data.clone();
768        assert_eq!(
769            reader.stored_block(&data).unwrap_err().kind(),
770            ErrorKind::BadAttribute,
771            "an absolute path was followed without being asked for"
772        );
773
774        reader.follow_absolute_paths(true);
775        assert_eq!(&*reader.stored_block(&data).unwrap(), b"payload");
776
777        let _ = std::fs::remove_dir_all(&dir);
778    }
779
780    // Needs a hash implementation compiled in; without the feature the
781    // library correctly refuses rather than pretending to verify.
782    /// A remote block is refused until the caller says how to fetch it, and
783    /// the resolver sees the URL exactly as the file wrote it -- which is
784    /// what lets a caller apply a policy rather than trusting the file.
785    #[test]
786    fn url_blocks_need_a_resolver_the_caller_installs() {
787        let xml =
788            r#"<xisf version="1.0"><Image location="url(https://example.com/b.dat)"/></xisf>"#;
789        let mut reader = Reader::from_bytes(header_file(xml)).unwrap();
790        let data = reader.header().images()[0].data.clone();
791
792        let err = reader.stored_block(&data).unwrap_err();
793        assert_eq!(err.kind(), ErrorKind::Unsupported);
794        assert!(err.message().contains("set_url_resolver"), "{}", err.message());
795
796        // With a resolver, the URL arrives verbatim.
797        reader.set_url_resolver(|url| {
798            assert_eq!(url, "https://example.com/b.dat");
799            Ok(b"fetched".to_vec())
800        });
801        assert_eq!(&*reader.stored_block(&data).unwrap(), b"fetched");
802
803        // And a resolver may refuse, which must surface rather than be eaten.
804        reader.set_url_resolver(|url| {
805            Err(crate::Error::new(ErrorKind::Unsupported, format!("refusing {url}")))
806        });
807        assert!(reader.stored_block(&data).unwrap_err().message().contains("refusing"));
808
809        reader.clear_url_resolver();
810        assert_eq!(reader.stored_block(&data).unwrap_err().kind(), ErrorKind::Unsupported);
811    }
812
813    /// A remote data blocks file is addressed by identifier exactly as a
814    /// local one is, so the resolver only has to supply bytes.
815    #[test]
816    fn a_remote_blocks_file_is_addressed_by_identifier() {
817        use crate::distributed::PendingBlock;
818        let blocks = crate::distributed::write_blocks_file(&[
819            PendingBlock { id: 1, bytes: b"first".to_vec(), uncompressed_length: None },
820            PendingBlock { id: 0x2a, bytes: b"the wanted one".to_vec(), uncompressed_length: None },
821        ])
822        .unwrap();
823
824        let xml = r#"<xisf version="1.0"><Image location="url(https://h/b.xisb):0x2a"/></xisf>"#;
825        let mut reader = Reader::from_bytes(header_file(xml)).unwrap();
826        reader.set_url_resolver(move |_| Ok(blocks.clone()));
827
828        let data = reader.header().images()[0].data.clone();
829        assert_eq!(&*reader.stored_block(&data).unwrap(), b"the wanted one");
830    }
831
832    #[test]
833    fn checksums_are_over_the_stored_bytes() {
834        let digest = digest_hex(&digest(b"ABC", ChecksumAlgorithm::Sha256).unwrap());
835        let xml = format!(
836            r#"<xisf version="1.0"><Image location="inline:base64" checksum="sha-256:{digest}">QUJD</Image></xisf>"#
837        );
838        let reader = Reader::from_bytes(build(&xml, &[])).unwrap();
839        let image = reader.header().images()[0];
840        assert_eq!(reader.verify(&image.data).unwrap(), ChecksumStatus::Valid);
841    }
842
843    #[test]
844    fn a_wrong_checksum_is_reported_not_ignored() {
845        let xml = format!(
846            r#"<xisf version="1.0"><Image location="inline:base64" checksum="sha-256:{}">QUJD</Image></xisf>"#,
847            "00".repeat(32)
848        );
849        let reader = Reader::from_bytes(build(&xml, &[])).unwrap();
850        let image = reader.header().images()[0];
851        assert_eq!(reader.verify(&image.data).unwrap(), ChecksumStatus::Invalid);
852    }
853
854    #[test]
855    fn no_checksum_is_not_a_failure() {
856        let xml = r#"<xisf version="1.0"><Image location="inline:base64">QUJD</Image></xisf>"#;
857        let reader = Reader::from_bytes(build(xml, &[])).unwrap();
858        let image = reader.header().images()[0];
859        assert_eq!(reader.verify(&image.data).unwrap(), ChecksumStatus::Absent);
860    }
861}