torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use crate::error::{Error, Result};
use crate::torrent::TorrentInfo;

pub fn validate_block_request(
    info: &TorrentInfo,
    piece: u32,
    begin: u32,
    length: u32,
    block_size: u32,
) -> Result<()> {
    if piece >= info.piece_count() {
        return Err(Error::Peer(format!("piece index {piece} out of range")));
    }
    if length == 0 || length > block_size {
        return Err(Error::Peer(format!("block length {length} invalid")));
    }
    let piece_size = info.piece_size(piece);
    if begin >= piece_size {
        return Err(Error::Peer(format!("block begin {begin} past piece end")));
    }
    if begin > 0 && !begin.is_multiple_of(block_size) {
        return Err(Error::Peer(format!(
            "block begin {begin} is not aligned to block size {block_size}"
        )));
    }
    if begin.saturating_add(length) > piece_size {
        return Err(Error::Peer("block extends past piece boundary".into()));
    }
    Ok(())
}

pub fn validate_piece_block_write(
    info: &TorrentInfo,
    piece: u32,
    begin: u32,
    data_len: usize,
    block_size: u32,
) -> Result<()> {
    validate_block_request(
        info,
        piece,
        begin,
        data_len.min(u32::MAX as usize) as u32,
        block_size,
    )
}

pub fn validate_upload_request(
    info: &TorrentInfo,
    piece: u32,
    begin: u32,
    length: u32,
    block_size: u32,
) -> Result<()> {
    validate_block_request(info, piece, begin, length, block_size)
}

pub fn validate_metadata_piece(piece: u32, total_size: u32, data_len: usize) -> Result<()> {
    if total_size == 0 || total_size as usize > crate::security::MAX_METADATA_BYTES {
        return Err(Error::Metadata("metadata total_size out of bounds".into()));
    }
    let start = piece as u64 * 16 * 1024;
    if start >= total_size as u64 {
        return Err(Error::Metadata("metadata piece index out of range".into()));
    }
    let end = start.saturating_add(data_len as u64);
    if end > total_size as u64 {
        return Err(Error::Metadata("metadata piece overruns total_size".into()));
    }
    Ok(())
}

/// Reject values that would break HTTP request line / header framing (CRLF / NUL).
pub fn reject_http_token(label: &str, value: &str) -> Result<()> {
    if value
        .as_bytes()
        .iter()
        .any(|b| matches!(b, b'\r' | b'\n' | 0))
    {
        return Err(Error::Session(format!(
            "{label} contains forbidden control characters"
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::torrent::{InfoHash, TorrentInfo};
    use std::path::PathBuf;

    fn sample_info(pieces: u32) -> TorrentInfo {
        TorrentInfo {
            info_hash: InfoHash::from_bytes([0; 20]),
            info_hash_v2: None,
            name: "x".into(),
            piece_length: 16_384,
            pieces: vec![[0; 20]; pieces as usize],
            files: vec![(PathBuf::from("x"), pieces as u64 * 16_384)],
            total_len: pieces as u64 * 16_384,
            private: false,
            meta_version: crate::torrent::MetaVersion::V1,
            v2: None,
        }
    }

    #[test]
    fn rejects_out_of_range_piece() {
        let info = sample_info(1);
        assert!(validate_block_request(&info, 1, 0, 16384, 16384).is_err());
    }

    #[test]
    fn rejects_block_past_piece_end() {
        let info = sample_info(1);
        assert!(validate_block_request(&info, 0, 16_000, 16384, 16384).is_err());
    }
}