torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

use crate::error::{Error, Result};

/// On-disk source mapped to torrent-relative paths (used by create + verify).
#[derive(Debug, Clone)]
pub struct ContentSource {
    pub absolute: PathBuf,
    pub relative: PathBuf,
    pub length: u64,
    /// BEP 47 padding file — reads as zeros; may have no on-disk path.
    pub is_pad: bool,
}

#[derive(Debug, Clone)]
pub struct ContentLayout {
    pub name: String,
    pub files: Vec<ContentSource>,
    pub total_len: u64,
}

impl ContentLayout {
    pub fn from_path(input: impl AsRef<Path>, name_override: Option<String>) -> Result<Self> {
        let input = input.as_ref();
        if !input.exists() {
            return Err(Error::Torrent(format!("path does not exist: {}", input.display())));
        }

        let (name, files) = if input.is_file() {
            let file_name = input
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| Error::Torrent("file name is not valid utf-8".into()))?;
            let torrent_name = name_override.unwrap_or_else(|| file_name.to_string());
            let length = input.metadata()?.len();
            (
                torrent_name.clone(),
                vec![ContentSource {
                    absolute: input.to_path_buf(),
                    relative: PathBuf::from(&torrent_name),
                    length,
                    is_pad: false,
                }],
            )
        } else if input.is_dir() {
            let torrent_name = name_override
                .or_else(|| {
                    input
                        .file_name()
                        .and_then(|n| n.to_str())
                        .map(str::to_string)
                })
                .ok_or_else(|| Error::Torrent("directory name is not valid utf-8".into()))?;
            let mut files = Vec::new();
            collect_directory_files(input, input, &torrent_name, &mut files)?;
            files.sort_by(|a, b| a.relative.cmp(&b.relative));
            (torrent_name, files)
        } else {
            return Err(Error::Torrent(format!(
                "path is not a regular file or directory: {}",
                input.display()
            )));
        };

        if files.is_empty() {
            return Err(Error::Torrent("no files to include".into()));
        }

        let total_len = files
            .iter()
            .map(|f| f.length)
            .try_fold(0u64, u64::checked_add)
            .ok_or_else(|| Error::Torrent("content total size overflow".into()))?;

        if total_len == 0 {
            return Err(Error::Torrent("cannot use empty content".into()));
        }

        Ok(Self {
            name,
            files,
            total_len,
        })
    }

    pub fn from_torrent_at(base: impl AsRef<Path>, info: &crate::torrent::TorrentInfo) -> Result<Self> {
        let base = base.as_ref();
        let mut files = Vec::with_capacity(info.files.len());
        for (relative, length) in &info.files {
            let is_pad = crate::torrent::v2::is_pad_path(relative);
            files.push(ContentSource {
                absolute: if is_pad {
                    PathBuf::new()
                } else {
                    base.join(relative)
                },
                relative: relative.clone(),
                length: *length,
                is_pad,
            });
        }
        if files.is_empty() {
            return Err(Error::Torrent("torrent has no files".into()));
        }
        let total_len = info.total_len;
        Ok(Self {
            name: info.name.clone(),
            files,
            total_len,
        })
    }

    pub fn torrent_files(&self) -> Vec<(PathBuf, u64)> {
        self.files
            .iter()
            .map(|f| (f.relative.clone(), f.length))
            .collect()
    }

    pub fn read_bytes(&self, mut offset: u64, len: usize) -> Result<Vec<u8>> {
        let mut out = vec![0u8; len];
        let mut written = 0usize;
        let mut cursor = 0u64;

        for file in &self.files {
            if written >= len {
                break;
            }

            let file_end = cursor
                .checked_add(file.length)
                .ok_or_else(|| Error::Torrent("file offset overflow while reading content".into()))?;

            if offset >= file_end {
                cursor = file_end;
                continue;
            }

            let skip = offset
                .checked_sub(cursor)
                .ok_or_else(|| Error::Torrent("negative in-file offset".into()))?;

            if file.is_pad {
                while written < len && offset < file_end {
                    let available = len - written;
                    let remaining_in_file = (file_end - offset) as usize;
                    let chunk_len = available.min(remaining_in_file);
                    out[written..written + chunk_len].fill(0);
                    written += chunk_len;
                    offset = offset.saturating_add(chunk_len as u64);
                }
                cursor = file_end;
                continue;
            }

            let mut handle = File::open(&file.absolute)?;
            handle.seek(SeekFrom::Start(skip))?;

            while written < len && offset < file_end {
                let available = len - written;
                let remaining_in_file = (file_end - offset) as usize;
                let chunk_len = available.min(remaining_in_file);

                handle.read_exact(&mut out[written..written + chunk_len])?;
                written += chunk_len;
                offset = offset.saturating_add(chunk_len as u64);
            }

            cursor = file_end;
        }

        if written != len {
            return Err(Error::Torrent(
                "unexpected end of content while reading bytes".into(),
            ));
        }
        Ok(out)
    }

    pub fn read_piece(&self, piece_index: u32, piece_length: u32) -> Result<Vec<u8>> {
        let piece_length = piece_length as u64;
        let start = (piece_index as u64)
            .checked_mul(piece_length)
            .ok_or_else(|| Error::Torrent("piece offset overflow".into()))?;
        if start >= self.total_len {
            return Err(Error::Torrent("piece index out of range".into()));
        }
        let len = piece_length
            .min(self.total_len.saturating_sub(start))
            .try_into()
            .map_err(|_| Error::Torrent("piece length does not fit in usize".into()))?;
        self.read_bytes(start, len)
    }
}

fn collect_directory_files(
    root: &Path,
    current: &Path,
    torrent_name: &str,
    out: &mut Vec<ContentSource>,
) -> Result<()> {
    for entry in std::fs::read_dir(current)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_directory_files(root, &path, torrent_name, out)?;
            continue;
        }
        if !path.is_file() {
            continue;
        }

        let relative = path
            .strip_prefix(root)
            .map_err(|_| Error::Torrent(format!("failed to relativize {}", path.display())))?
            .to_path_buf();
        out.push(ContentSource {
            absolute: path,
            relative: PathBuf::from(torrent_name).join(relative),
            length: entry.metadata()?.len(),
            is_pad: false,
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reads_piece_from_single_file() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("data.bin");
        std::fs::write(&path, b"abcdefghij").expect("write");
        let layout = ContentLayout::from_path(&path, None).expect("layout");
        let piece = layout.read_piece(0, 16 * 1024).expect("piece");
        assert_eq!(piece, b"abcdefghij");
    }
}