use std::path::{Path, PathBuf};
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
use crate::error::{Error, Result};
use crate::torrent::TorrentInfo;
#[derive(Debug, Clone)]
struct FileSlice {
relative: PathBuf,
offset: u64,
length: u64,
}
#[derive(Debug, Clone)]
pub struct DiskTier {
root: PathBuf,
slices: Vec<FileSlice>,
total_len: u64,
}
impl DiskTier {
pub async fn open(root: impl AsRef<Path>, info: &TorrentInfo) -> Result<Self> {
if info.total_len > crate::security::MAX_TORRENT_CONTENT_BYTES {
return Err(Error::Store(format!(
"torrent total length {} exceeds maximum {}",
info.total_len,
crate::security::MAX_TORRENT_CONTENT_BYTES
)));
}
let download_root = root.as_ref();
if !tokio::fs::try_exists(download_root).await.unwrap_or(false) {
tokio::fs::create_dir_all(download_root).await?;
}
let root_meta = tokio::fs::symlink_metadata(download_root).await?;
if root_meta.file_type().is_symlink() || !root_meta.is_dir() {
return Err(Error::Store(format!(
"download root must be a real directory: {}",
download_root.display()
)));
}
let hash_rel = PathBuf::from(info.info_hash.to_hex());
crate::security::ensure_dir_under_root(download_root, &hash_rel)?;
let root = download_root.join(&hash_rel);
let mut slices = Vec::with_capacity(info.files.len());
let mut torrent_offset = 0u64;
for (relative, length) in &info.files {
if *length > crate::security::MAX_TORRENT_CONTENT_BYTES {
return Err(Error::Store(format!(
"file length {length} exceeds maximum {}",
crate::security::MAX_TORRENT_CONTENT_BYTES
)));
}
let relative = crate::security::sanitize_torrent_relative_path(relative)?;
crate::security::create_content_with_len_async(&root, &relative, *length).await?;
slices.push(FileSlice {
relative,
offset: torrent_offset,
length: *length,
});
torrent_offset = torrent_offset
.checked_add(*length)
.ok_or_else(|| Error::Store("file layout length overflow".into()))?;
}
if torrent_offset != info.total_len {
return Err(Error::Store(format!(
"file layout length {torrent_offset} does not match torrent total {}",
info.total_len
)));
}
Ok(Self {
root,
slices,
total_len: info.total_len,
})
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn read_at_sync(&self, absolute_offset: u64, len: usize) -> Result<Vec<u8>> {
if absolute_offset >= self.total_len {
return Ok(Vec::new());
}
let len = len.min((self.total_len - absolute_offset) as usize);
let mut buf = vec![0u8; len];
self.read_into_sync(absolute_offset, &mut buf)?;
Ok(buf)
}
pub async fn read_at(&self, absolute_offset: u64, len: usize) -> Result<Bytes> {
if absolute_offset >= self.total_len {
return Ok(Bytes::new());
}
let len = len.min((self.total_len - absolute_offset) as usize);
let mut buf = vec![0u8; len];
self.read_into(absolute_offset, &mut buf).await?;
Ok(Bytes::from(buf))
}
pub async fn write_at(&self, mut absolute_offset: u64, data: &[u8]) -> Result<()> {
if data.is_empty() {
return Ok(());
}
if absolute_offset.saturating_add(data.len() as u64) > self.total_len {
return Err(Error::Store("write extends past torrent end".into()));
}
let mut written = 0usize;
for slice in &self.slices {
if written >= data.len() {
break;
}
let slice_end = slice.offset.saturating_add(slice.length);
if absolute_offset >= slice_end {
continue;
}
let in_slice = absolute_offset.saturating_sub(slice.offset);
if in_slice >= slice.length {
continue;
}
let mut file =
crate::security::open_content_rw_async(&self.root, &slice.relative).await?;
file.seek(std::io::SeekFrom::Start(in_slice)).await?;
let available = data.len() - written;
let chunk_len = available.min((slice.length - in_slice) as usize);
file.write_all(&data[written..written + chunk_len]).await?;
written += chunk_len;
absolute_offset = absolute_offset.saturating_add(chunk_len as u64);
}
Ok(())
}
fn read_into_sync(&self, mut absolute_offset: u64, buf: &mut [u8]) -> Result<()> {
use std::io::{Read, Seek, SeekFrom};
let mut read_total = 0usize;
for slice in &self.slices {
if read_total >= buf.len() {
break;
}
let slice_end = slice.offset.saturating_add(slice.length);
if absolute_offset >= slice_end {
continue;
}
let in_slice = absolute_offset.saturating_sub(slice.offset);
if in_slice >= slice.length {
continue;
}
let mut file = crate::security::open_content_read(&self.root, &slice.relative)?;
file.seek(SeekFrom::Start(in_slice))?;
let available = buf.len() - read_total;
let chunk_len = available.min((slice.length - in_slice) as usize);
file.read_exact(&mut buf[read_total..read_total + chunk_len])?;
read_total += chunk_len;
absolute_offset = absolute_offset.saturating_add(chunk_len as u64);
}
Ok(())
}
async fn read_into(&self, mut absolute_offset: u64, buf: &mut [u8]) -> Result<()> {
let mut read_total = 0usize;
for slice in &self.slices {
if read_total >= buf.len() {
break;
}
let slice_end = slice.offset.saturating_add(slice.length);
if absolute_offset >= slice_end {
continue;
}
let in_slice = absolute_offset.saturating_sub(slice.offset);
if in_slice >= slice.length {
continue;
}
let mut file =
crate::security::open_content_read_async(&self.root, &slice.relative).await?;
file.seek(std::io::SeekFrom::Start(in_slice)).await?;
let available = buf.len() - read_total;
let chunk_len = available.min((slice.length - in_slice) as usize);
file.read_exact(&mut buf[read_total..read_total + chunk_len])
.await?;
read_total += chunk_len;
absolute_offset = absolute_offset.saturating_add(chunk_len as u64);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::torrent::{InfoHash, TorrentInfo};
use std::path::PathBuf;
fn sample_info() -> TorrentInfo {
TorrentInfo {
info_hash: InfoHash::from_bytes([1; 20]),
info_hash_v2: None,
name: "sample".into(),
piece_length: 16384,
pieces: vec![[0; 20]],
files: vec![(PathBuf::from("sample.bin"), 32)],
total_len: 32,
private: false,
meta_version: crate::torrent::MetaVersion::V1,
v2: None,
}
}
#[tokio::test]
async fn roundtrip_write_read() {
let dir = tempfile::tempdir().expect("tempdir");
let tier = DiskTier::open(dir.path(), &sample_info())
.await
.expect("open");
tier.write_at(0, b"hello world").await.expect("write");
let data = tier.read_at(0, 5).await.expect("read");
assert_eq!(&data[..], b"hello");
}
#[tokio::test]
async fn rejects_symlink_content_file() {
let dir = tempfile::tempdir().expect("tempdir");
let info = sample_info();
let root = dir.path().join(info.info_hash.to_hex());
tokio::fs::create_dir_all(&root).await.expect("mkdir");
let outside = dir.path().join("outside.bin");
tokio::fs::write(&outside, b"leak").await.expect("outside");
#[cfg(unix)]
{
tokio::fs::symlink(&outside, root.join("sample.bin"))
.await
.expect("symlink");
let err = DiskTier::open(dir.path(), &info).await;
assert!(err.is_err(), "symlink content must be rejected");
}
}
}