1use 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
15pub type UrlResolver = Box<dyn Fn(&str) -> Result<Vec<u8>> + Send + Sync>;
18
19#[derive(Clone, Copy, PartialEq, Eq, Debug)]
21pub enum ChecksumStatus {
22 Absent,
25 Valid,
26 Invalid,
27}
28
29impl ChecksumStatus {
30 pub fn is_failure(self) -> bool {
31 self == ChecksumStatus::Invalid
32 }
33}
34
35enum Source {
37 #[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
67pub struct Reader {
69 source: Source,
70 layout: Layout,
71 header: Header,
72 allow_absolute_paths: bool,
74 url_resolver: Option<UrlResolver>,
76 verify_checksums: bool,
78 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 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
112 let path = path.as_ref();
113
114 #[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 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 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 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 pub fn stored_block(&self, data: &DataRef) -> Result<Cow<'_, [u8]>> {
203 let stored = self.stored_block_unchecked(data)?;
204
205 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 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 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 let text = data.text.as_deref().unwrap_or("");
269 Ok(Cow::Owned(decode_text(text, *encoding)?))
270 }
271 Location::Embedded { encoding } => {
272 let text = data.text.as_deref().unwrap_or("");
275 Ok(Cow::Owned(decode_text(text, *encoding)?))
276 }
277
278 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 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 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 pub fn set_verify_checksums(&mut self, verify: bool) {
357 self.verify_checksums = verify;
358 }
359
360 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 pub fn clear_url_resolver(&mut self) {
407 self.url_resolver = None;
408 }
409
410 pub fn follow_absolute_paths(&mut self, allow: bool) {
424 self.allow_absolute_paths = allow;
425 }
426
427 fn resolve_relative(&self, locator: &str) -> Result<PathBuf> {
433 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 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 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
516fn 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 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 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 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
560fn 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
613fn 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 crate::block::decode_hex(compact.as_bytes())
628 .ok_or_else(|| err!(BadAttribute, "hex data is not hexadecimal"))
629 }
630 }
631}
632
633pub 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 ChecksumAlgorithm::Sha3_256 => sha3::Sha3_256::digest(bytes).to_vec(),
650 ChecksumAlgorithm::Sha3_512 => sha3::Sha3_512::digest(bytes).to_vec(),
651 })
652}
653
654pub fn digest_hex(digest: &[u8]) -> String {
656 digest.iter().map(|b| format!("{b:02x}")).collect()
657}
658
659pub 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 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 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 #[test]
721 fn a_block_may_not_address_outside_the_file() {
722 for location in [
723 "attachment:0:10", "attachment:100000:1", "attachment:18446744073709551615:1", ] {
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 #[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 #[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 #[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 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 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 #[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}