Skip to main content

aff4_image/
disk.rs

1//! Explicit physical-image selection and a seekable decoded-media cursor.
2use std::io::{self, Read, Seek, SeekFrom};
3
4use crate::{Container, Error, Result};
5
6const DISK: &str = "http://aff4.org/Schema#DiskImage";
7const BLOCK_SIZE: &str = "http://aff4.org/Schema#blockSize";
8
9/// Identity and geometry of a selected physical AFF4 image, not its ZIP file.
10#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
11pub struct DiskImageInfo {
12    /// Selected DiskImage resource identifier.
13    pub resource_id: String,
14    /// Owning container identifier.
15    pub volume_id: String,
16    /// Decoded image length; this can differ from underlying stream lengths.
17    pub logical_size: u64,
18    /// Declared `blockSize`, when present. Never inferred from chunk size.
19    pub block_size: Option<u32>,
20}
21
22impl Container {
23    /// Enumerates explicitly typed physical images in a single AFF4 1.0 volume.
24    /// Storage streams, logical files, and memory images are not disk candidates.
25    /// Invalid image sizes or contradictory block sizes are errors, not omissions.
26    pub fn disk_images(&self) -> Result<Vec<DiskImageInfo>> {
27        if self.version() != (1, 0) {
28            return Err(Error::Unsupported(
29                "disk reading requires physical AFF4 1.0; logical collections are not disks".into(),
30            ));
31        }
32        self.streams()?
33            .into_iter()
34            .filter(|stream| stream.types.iter().any(|kind| kind == DISK))
35            .map(|stream| {
36                if stream.types.iter().any(|kind| {
37                    ["MemoryImage", "FileImage", "FileSubStream"]
38                        .iter()
39                        .any(|name| {
40                            kind == &format!("http://aff4.org/Schema#{name}")
41                                || kind == &format!("https://aff4.org/Schema/2022/#{name}")
42                                || kind == &format!("http://aff4.org/Schema/2022/#{name}")
43                        })
44                }) {
45                    return Err(crate::malformed("conflicting disk resource types"));
46                }
47                let mut block_size = None;
48                for property in &self.metadata()[&stream.id] {
49                    if property.predicate != BLOCK_SIZE {
50                        continue;
51                    }
52                    let value = property
53                        .value
54                        .parse::<u32>()
55                        .ok()
56                        .filter(|value| *value > 0)
57                        .ok_or_else(|| crate::malformed("invalid disk blockSize"))?;
58                    if block_size.is_some_and(|previous| previous != value) {
59                        return Err(crate::malformed("conflicting disk blockSize values"));
60                    }
61                    block_size = Some(value);
62                }
63                Ok(DiskImageInfo {
64                    logical_size: self.size(&stream.id)?,
65                    resource_id: stream.id,
66                    volume_id: self.volume_id().to_owned(),
67                    block_size,
68                })
69            })
70            .collect()
71    }
72
73    /// Selects a physical image by identifier and transfers this container to a cursor.
74    /// With `None`, exactly one disk candidate is required. Selection never chooses
75    /// an underlying ImageStream or Map. Opening does not verify the whole image.
76    pub fn into_disk_reader(self, resource: Option<&str>) -> Result<DiskImageReader> {
77        let candidates = self.disk_images()?;
78        let info = match resource {
79            Some(id) => candidates
80                .into_iter()
81                .find(|info| info.resource_id == id)
82                .ok_or_else(|| {
83                    Error::Unsupported("selected resource is not a physical DiskImage".into())
84                })?,
85            None if candidates.len() == 1 => candidates.into_iter().next().unwrap(),
86            None => {
87                return Err(Error::Unsupported(format!(
88                    "expected one physical DiskImage, found {}; select a resource identifier: {}",
89                    candidates.len(),
90                    candidates
91                        .iter()
92                        .take(8)
93                        .map(|info| info.resource_id.as_str())
94                        .collect::<Vec<_>>()
95                        .join(", ")
96                )));
97            }
98        };
99        Ok(DiskImageReader {
100            container: self,
101            info,
102            position: 0,
103        })
104    }
105}
106
107/// Owned read-only cursor over one physical image's decoded bytes.
108/// Reads retain normal AFF4 limits and errors, including missing/unreadable ranges.
109/// Backing files must remain unchanged. Seeking does not read or verify data.
110pub struct DiskImageReader {
111    container: Container,
112    info: DiskImageInfo,
113    position: u64,
114}
115
116impl DiskImageReader {
117    /// Selected resource identity and declared geometry.
118    pub fn info(&self) -> &DiskImageInfo {
119        &self.info
120    }
121
122    /// Reads logical bytes without changing the cursor position.
123    pub fn read_at(&mut self, buffer: &mut [u8], offset: u64) -> Result<usize> {
124        self.container
125            .read_at(&self.info.resource_id, buffer, offset)
126    }
127}
128
129impl Read for DiskImageReader {
130    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
131        let count = self
132            .read_at(buffer, self.position)
133            .map_err(io::Error::other)?;
134        self.position += count as u64;
135        Ok(count)
136    }
137}
138
139impl Seek for DiskImageReader {
140    fn seek(&mut self, from: SeekFrom) -> io::Result<u64> {
141        let position = match from {
142            SeekFrom::Start(offset) => Some(offset),
143            SeekFrom::End(offset) => self.info.logical_size.checked_add_signed(offset),
144            SeekFrom::Current(offset) => self.position.checked_add_signed(offset),
145        }
146        .ok_or_else(|| {
147            io::Error::new(io::ErrorKind::InvalidInput, "AFF4 seek outside u64 range")
148        })?;
149        self.position = position;
150        Ok(position)
151    }
152}