libpfs3 0.1.1

Pure Rust PFS3 (Amiga) filesystem library — read, write, format, and check
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! PFS3 volume: top-level read-only access to a PFS3 partition.

use std::path::Path;

use crate::anode::AnodeReader;
use crate::bitmap::BitmapReader;
use crate::cache::BlockCache;
use crate::dir;
use crate::error::{Error, Result};
use crate::io::{BlockDevice, FileBlockDevice};
use crate::ondisk::*;
use crate::rdb::detect_pfs3_partition;

/// A mounted PFS3 volume providing read access to files and directories.
pub struct Volume {
    pub(crate) dev: Box<dyn BlockDevice>,
    pub(crate) cache: BlockCache,
    pub rootblock: Rootblock,
    pub rootblock_ext: Option<RootblockExt>,
    pub(crate) anodes: AnodeReader,
    pub(crate) bitmap: BitmapReader,
}

impl Volume {
    /// Validate reserved block size is sane (prevents div-by-zero downstream).
    fn validate_rbs(rb: &Rootblock) -> Result<()> {
        if rb.reserved_blksize < 64 {
            return Err(Error::Corrupt(format!(
                "reserved_blksize {} too small (minimum 64)",
                rb.reserved_blksize
            )));
        }
        Ok(())
    }

    /// Open a PFS3 volume from an already-opened block device.
    pub fn from_device(dev: Box<dyn BlockDevice>) -> Result<Self> {
        let mut buf = vec![0u8; 512];
        dev.read_block(ROOTBLOCK, &mut buf)?;
        let rb = Rootblock::parse(&buf)?;

        let rblk_bytes = rb.rblkcluster as u32 * 512;
        let rootblock = if rblk_bytes > 512 {
            let mut big_buf = vec![0u8; rblk_bytes as usize];
            dev.read_blocks(ROOTBLOCK, rb.rblkcluster as u32, &mut big_buf)?;
            Rootblock::parse(&big_buf)?
        } else {
            rb
        };

        let mut cache = BlockCache::new();
        let rootblock_ext = if rootblock.has_extension() {
            let rbs = rootblock.reserved_blksize;
            let data = cache.read_reserved(dev.as_ref(), rootblock.extension as u64, rbs)?;
            Some(RootblockExt::parse(data)?)
        } else {
            None
        };

        let anodes = AnodeReader::new(&rootblock, rootblock_ext.as_ref());
        let bitmap = BitmapReader::new(&rootblock);
        Self::validate_rbs(&rootblock)?;

        Ok(Self {
            dev,
            cache,
            rootblock,
            rootblock_ext,
            anodes,
            bitmap,
        })
    }

    /// Open a PFS3 volume from a file.
    /// `partition_offset` is the byte offset to the partition start (0 for raw PFS3 images).
    pub fn open(path: &Path, partition_offset: u64) -> Result<Self> {
        Self::open_impl(path, partition_offset, false)
    }

    /// Open a PFS3 volume for read-write access.
    pub fn open_rw(path: &Path, partition_offset: u64) -> Result<Self> {
        Self::open_impl(path, partition_offset, true)
    }

    fn open_impl(path: &Path, partition_offset: u64, writable: bool) -> Result<Self> {
        let dev = if writable {
            FileBlockDevice::open_rw(path, 512, partition_offset, 0)?
        } else {
            FileBlockDevice::open(path, 512, partition_offset, 0)?
        };
        Self::from_device(Box::new(dev))
    }

    /// Open a PFS3 volume from an RDB disk image, auto-detecting the partition offset.
    pub fn open_rdb(path: &Path) -> Result<Self> {
        let offset = detect_pfs3_partition(path)?;
        Self::open(path, offset)
    }

    /// Open a specific named partition from an RDB disk image (e.g. "DH0").
    pub fn open_partition(path: &Path, name: &str) -> Result<Self> {
        Self::open(path, Self::find_partition_offset(path, name)?)
    }

    /// Open an RDB disk image for read-write access.
    pub fn open_rdb_rw(path: &Path) -> Result<Self> {
        let offset = detect_pfs3_partition(path)?;
        Self::open_rw(path, offset)
    }

    /// Open a named partition for read-write access.
    pub fn open_partition_rw(path: &Path, name: &str) -> Result<Self> {
        Self::open_rw(path, Self::find_partition_offset(path, name)?)
    }

    /// Open a volume with automatic partition/RDB detection.
    /// Unified entry point for CLI commands.
    pub fn open_auto(
        path: &Path,
        offset: u64,
        partition: Option<&str>,
        writable: bool,
    ) -> Result<Self> {
        let open_fn = if writable {
            Self::open_rw as fn(&Path, u64) -> Result<Self>
        } else {
            Self::open as fn(&Path, u64) -> Result<Self>
        };
        if let Some(name) = partition {
            open_fn(path, Self::find_partition_offset(path, name)?)
        } else if offset == 0 {
            let off = detect_pfs3_partition(path).unwrap_or(0);
            open_fn(path, off)
        } else {
            open_fn(path, offset)
        }
    }

    fn find_partition_offset(path: &Path, name: &str) -> Result<u64> {
        let parts = detect_pfs3_partitions(path)?;
        let part = parts
            .iter()
            .find(|p| p.name.eq_ignore_ascii_case(name))
            .or_else(|| name.parse::<usize>().ok().and_then(|i| parts.get(i)))
            .ok_or_else(|| {
                let names: Vec<_> = parts.iter().map(|p| p.name.as_str()).collect();
                Error::NotFound(format!(
                    "partition '{}' not found (available: {})",
                    name,
                    names.join(", ")
                ))
            })?;
        Ok(part.offset)
    }

    // --- Info ---

    /// Volume name from the rootblock.
    pub fn name(&self) -> &str {
        &self.rootblock.diskname
    }

    /// Total blocks on disk.
    pub fn total_blocks(&self) -> u32 {
        self.rootblock.disksize
    }

    /// Number of free data blocks.
    pub fn free_blocks(&self) -> u32 {
        self.rootblock.blocksfree
    }

    /// Block size in bytes.
    pub fn block_size(&self) -> u32 {
        self.dev.block_size()
    }

    /// Maximum filename length (32 or 107 with long filenames).
    pub fn fnsize(&self) -> u16 {
        self.rootblock_ext.as_ref().map(|e| e.fnsize).unwrap_or(32)
    }

    /// Count free blocks by scanning the data bitmap.
    pub fn bitmap_count_free(&mut self) -> Result<u32> {
        self.bitmap
            .count_free(self.dev.as_ref(), &mut self.cache, self.rootblock.disksize)
    }

    /// Get the anode chain for a given anode number (for check/debug).
    pub fn get_anode_chain(&mut self, anodenr: u32) -> Result<Vec<crate::ondisk::Anode>> {
        self.anodes
            .get_chain(anodenr, self.dev.as_ref(), &mut self.cache)
    }

    /// Count free reserved blocks by scanning the reserved bitmap in the rootblock cluster.
    pub fn reserved_count_free(&mut self) -> Result<u32> {
        let bs = self.block_size() as usize;
        let rblkcluster = self.rootblock.rblkcluster as u32;
        let cluster_size = rblkcluster as usize * bs;
        let mut cluster = vec![0u8; cluster_size];
        self.dev.read_blocks(
            self.rootblock.firstreserved as u64,
            rblkcluster,
            &mut cluster,
        )?;
        let bm_off = bs + 12; // bitmap starts after rootblock + 12-byte header
        let mut free = 0u32;
        let mut i = bm_off;
        while i + 4 <= cluster.len() {
            let word = u32::from_be_bytes(cluster[i..i + 4].try_into().unwrap());
            free += word.count_ones();
            i += 4;
        }
        Ok(free)
    }

    // --- Directory operations ---

    /// List directory entries at the given path.
    pub fn list_dir(&mut self, path: &str) -> Result<Vec<DirEntry>> {
        let dir_anode = dir::resolve_dir_path(
            path,
            &self.anodes,
            self.dev.as_ref(),
            &mut self.cache,
            self.rootblock.reserved_blksize,
        )?;
        self.list_dir_by_anode(dir_anode)
    }

    /// List directory entries by anode number.
    pub fn list_dir_by_anode(&mut self, dir_anode: u32) -> Result<Vec<DirEntry>> {
        dir::list_entries(
            dir_anode,
            &self.anodes,
            self.dev.as_ref(),
            &mut self.cache,
            self.rootblock.reserved_blksize,
        )
    }

    /// Look up a directory entry by path. Returns `None` for root.
    pub fn lookup(&mut self, path: &str) -> Result<Option<DirEntry>> {
        dir::resolve_path(
            path,
            &self.anodes,
            self.dev.as_ref(),
            &mut self.cache,
            self.rootblock.reserved_blksize,
        )
    }

    // --- File reading ---

    /// Read a file's contents by path.
    pub fn read_file(&mut self, path: &str) -> Result<Vec<u8>> {
        let entry = self
            .lookup(path)?
            .ok_or_else(|| Error::NotFound(path.to_string()))?;
        if entry.is_dir() {
            return Err(Error::NotADirectory);
        }
        self.read_file_data(entry.anode, entry.file_size())
    }

    /// Read file data by anode number and known size.
    pub fn read_file_data(&mut self, anodenr: u32, size: u64) -> Result<Vec<u8>> {
        let chain = self
            .anodes
            .get_chain(anodenr, self.dev.as_ref(), &mut self.cache)?;
        let bs = self.dev.block_size() as u64;
        let mut data = Vec::with_capacity(size as usize);
        let mut remaining = size;

        let mut block_buf = vec![0u8; bs as usize];
        for an in &chain {
            for i in 0..an.clustersize {
                if remaining == 0 {
                    break;
                }
                let blk = an.blocknr as u64 + i as u64;
                self.dev.read_block(blk, &mut block_buf)?;
                let chunk = (remaining).min(bs) as usize;
                data.extend_from_slice(&block_buf[..chunk]);
                remaining -= chunk as u64;
            }
        }
        Ok(data)
    }

    /// Read a byte range from a file without loading the entire file.
    /// Only reads the blocks that overlap [offset, offset+length).
    pub fn read_file_range(
        &mut self,
        anodenr: u32,
        file_size: u64,
        offset: u64,
        length: u32,
    ) -> Result<Vec<u8>> {
        if offset >= file_size {
            return Ok(Vec::new());
        }
        let end = (offset + length as u64).min(file_size);
        let bs = self.dev.block_size() as u64;
        let chain = self
            .anodes
            .get_chain(anodenr, self.dev.as_ref(), &mut self.cache)?;

        let mut result = Vec::with_capacity((end - offset) as usize);
        let mut block_pos: u64 = 0; // byte position of current extent start
        let mut block_buf = vec![0u8; bs as usize];

        for an in &chain {
            let extent_bytes = an.clustersize as u64 * bs;
            let extent_end = block_pos + extent_bytes;

            // Skip extents entirely before our range
            if extent_end <= offset {
                block_pos = extent_end;
                continue;
            }
            // Stop if we've read enough
            if block_pos >= end {
                break;
            }

            for i in 0..an.clustersize {
                let blk_start = block_pos + i as u64 * bs;
                let blk_end = blk_start + bs;
                if blk_end <= offset {
                    continue;
                }
                if blk_start >= end {
                    break;
                }
                self.dev
                    .read_block(an.blocknr as u64 + i as u64, &mut block_buf)?;
                let slice_start = if offset > blk_start {
                    (offset - blk_start) as usize
                } else {
                    0
                };
                let slice_end = if end < blk_end {
                    (end - blk_start) as usize
                } else {
                    bs as usize
                };
                result.extend_from_slice(&block_buf[slice_start..slice_end]);
            }
            block_pos = extent_end;
        }
        Ok(result)
    }
    /// Walk an anode chain and return all data block numbers. For fsck.
    pub fn validate_anode_chain(&mut self, anodenr: u32) -> Result<Vec<u64>> {
        let chain = self
            .anodes
            .get_chain(anodenr, self.dev.as_ref(), &mut self.cache)?;
        let mut blocks = Vec::new();
        for an in &chain {
            for i in 0..an.clustersize {
                blocks.push(an.blocknr as u64 + i as u64);
            }
        }
        Ok(blocks)
    }

    /// List deleted files from the deldir (trash).
    pub fn list_deldir(&mut self) -> Result<Vec<DelDirEntry>> {
        if !self.rootblock.has_flag(MODE_DELDIR) {
            return Ok(Vec::new());
        }
        let rext = match &self.rootblock_ext {
            Some(e) => e,
            None => return Ok(Vec::new()),
        };
        let rbs = self.rootblock.reserved_blksize;
        let entries_per_block = deldir_entries_per_block(rbs);
        let mut result = Vec::new();
        for &blk in &rext.deldirblocks {
            if blk == 0 {
                continue;
            }
            let data = self
                .cache
                .read_reserved(self.dev.as_ref(), blk as u64, rbs)?;
            if u16::from_be_bytes(data[0..2].try_into().unwrap()) != DELDIRID {
                continue;
            }
            for i in 0..entries_per_block {
                let off = DELDIR_HEADER_SIZE + i * DELDIR_ENTRY_SIZE;
                if off + DELDIR_ENTRY_SIZE <= data.len()
                    && let Some(entry) = DelDirEntry::parse(&data[off..off + DELDIR_ENTRY_SIZE])
                {
                    result.push(entry);
                }
            }
        }
        Ok(result)
    }
}

// Re-export for backward compatibility
pub use crate::rdb::{PartitionInfo, detect_pfs3_partitions};