torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
use std::collections::BTreeMap;
use std::path::Path;

use crate::bencode::{decode, encode, BencodeValue};
use crate::error::{Error, Result};
use crate::integrity::{sign_info_dict, verify_info_dict, TorrentSignature};
use crate::torrent::info::{info_to_bencode, parse_info, TorrentInfo};
use ed25519_dalek::SigningKey;

#[derive(Debug, Clone)]
pub struct TorrentFile {
    pub announce: Option<String>,
    pub trackers: Vec<String>,
    pub web_seeds: Vec<String>,
    pub info: TorrentInfo,
    pub signature: Option<TorrentSignature>,
    /// Exact bencoded `info` dict bytes (for BEP 9 ut_metadata serve / hash fidelity).
    pub info_dict_bytes: Vec<u8>,
}

impl TorrentFile {
    pub fn parse(data: &[u8]) -> Result<Self> {
        let root = decode(data)?;
        Self::from_bencode(&root)
    }

    pub fn from_bencode(root: &BencodeValue) -> Result<Self> {
        let info_value = root
            .dict_get(b"info")
            .ok_or_else(|| Error::Torrent("missing info dict".into()))?
            .clone();
        let info_dict_bytes = encode(&info_value);
        let info = parse_info(&info_value)?;
        let announce = root
            .dict_get_str("announce")
            .and_then(|v| v.as_bytes())
            .and_then(|b| String::from_utf8(b.to_vec()).ok());
        let mut trackers = parse_announce_list(root);
        if let Some(url) = &announce {
            if !trackers.iter().any(|entry| entry == url) {
                trackers.insert(0, url.clone());
            }
        }
        let signature = root
            .dict_get(b"signature".as_ref())
            .map(TorrentSignature::from_bencode)
            .transpose()?;
        if let Some(sig) = &signature {
            verify_info_dict(&info_value, sig)?;
        }
        let web_seeds = parse_url_list(root);
        let mut info = info;
        if info.meta_version != crate::torrent::MetaVersion::V1 {
            let layers = crate::torrent::v2::parse_piece_layers_map(root)?;
            if let Some(tree_files) =
                crate::torrent::v2::parse_file_tree(&info_value, &info.name)?
            {
                info.v2 = Some(crate::torrent::v2::attach_piece_layers(
                    tree_files,
                    &layers,
                    info.piece_length,
                )?);
            } else if !layers.is_empty() {
                // Legacy hybrid without file tree: single/global piece layers.
                match crate::torrent::v2::parse_piece_layers_dict(root, info.piece_count())? {
                    Some(v2) => info.v2 = Some(v2),
                    None if info.meta_version == crate::torrent::MetaVersion::V2 => {
                        return Err(Error::Torrent(
                            "v2 torrent missing root piece layers".into(),
                        ));
                    }
                    None => {}
                }
            } else if info.meta_version == crate::torrent::MetaVersion::V2 {
                return Err(Error::Torrent(
                    "v2 torrent missing file tree / piece layers".into(),
                ));
            }
        }
        Ok(Self {
            announce,
            trackers,
            web_seeds,
            info,
            signature,
            info_dict_bytes,
        })
    }

    pub fn tracker_urls(&self) -> Vec<String> {
        self.trackers.clone()
    }

    pub fn ensure_trusted(
        &self,
        require_signature: bool,
        trusted_keys: &[[u8; 32]],
    ) -> Result<()> {
        if !require_signature {
            return Ok(());
        }
        let Some(sig) = &self.signature else {
            return Err(Error::Integrity(
                "torrent metadata is not signed".into(),
            ));
        };
        if trusted_keys.is_empty() {
            return Err(Error::Integrity(
                "require-signed-torrents needs at least one trusted-signing-key".into(),
            ));
        }
        if !trusted_keys.iter().any(|key| key == &sig.public_key) {
            return Err(Error::Integrity(
                "torrent signature public key is not in the trusted-signing-key allowlist".into(),
            ));
        }
        // Re-verify over the current info dict so mutated/crafted structs cannot bypass.
        verify_info_dict(&info_to_bencode(&self.info)?, sig)?;
        Ok(())
    }

    pub fn to_bencode(&self) -> Result<BencodeValue> {
        let mut root = BTreeMap::new();
        if let Some(announce) = &self.announce {
            root.insert(
                b"announce".to_vec(),
                BencodeValue::Bytes(announce.as_bytes().to_vec()),
            );
        }
        if self.trackers.len() > 1 {
            let tiers: Vec<BencodeValue> = self
                .trackers
                .iter()
                .map(|url| BencodeValue::List(vec![BencodeValue::Bytes(url.as_bytes().to_vec())]))
                .collect();
            root.insert(b"announce-list".to_vec(), BencodeValue::List(tiers));
        }
        root.insert(b"info".to_vec(), info_to_bencode(&self.info)?);
        if let Some(v2) = &self.info.v2 {
            root.insert(
                b"piece layers".to_vec(),
                crate::torrent::v2::piece_layers_to_bencode(v2),
            );
        }
        if !self.web_seeds.is_empty() {
            let list: Vec<BencodeValue> = self
                .web_seeds
                .iter()
                .map(|url| BencodeValue::Bytes(url.as_bytes().to_vec()))
                .collect();
            root.insert(b"url-list".to_vec(), BencodeValue::List(list));
        }
        if let Some(signature) = &self.signature {
            root.insert(
                b"signature".to_vec(),
                signature.to_bencode(),
            );
        }
        Ok(BencodeValue::Dict(root))
    }

    pub fn sign(&mut self, key: &SigningKey) {
        let Ok(info) = info_to_bencode(&self.info) else {
            return;
        };
        self.signature = Some(sign_info_dict(&info, key));
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        Ok(encode(&self.to_bencode()?))
    }

    pub async fn write_to(&self, path: impl AsRef<Path>) -> Result<()> {
        tokio::fs::write(path, self.to_bytes()?).await?;
        Ok(())
    }
}

fn parse_url_list(root: &BencodeValue) -> Vec<String> {
    let Some(value) = root.dict_get(b"url-list".as_ref()) else {
        return Vec::new();
    };
    if let Some(bytes) = value.as_bytes() {
        if let Ok(url) = String::from_utf8(bytes.to_vec()) {
            return vec![url];
        }
        return Vec::new();
    }
    if let Some(list) = value.as_list() {
        return list
            .iter()
            .filter_map(|entry| {
                entry
                    .as_bytes()
                    .and_then(|b| String::from_utf8(b.to_vec()).ok())
            })
            .collect();
    }
    Vec::new()
}

fn parse_announce_list(root: &BencodeValue) -> Vec<String> {
    let mut out = Vec::new();
    let Some(list) = root.dict_get(b"announce-list".as_ref()).and_then(|v| v.as_list()) else {
        return out;
    };
    for tier in list {
        let Some(urls) = tier.as_list() else {
            continue;
        };
        for entry in urls {
            if let Some(bytes) = entry.as_bytes() {
                if let Ok(url) = String::from_utf8(bytes.to_vec()) {
                    if !out.iter().any(|existing| existing == &url) {
                        out.push(url);
                    }
                }
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bencode::{encode, BencodeValue};
    use crate::integrity::signing_key_from_seed;
    use std::collections::BTreeMap;

    #[test]
    fn parses_single_file_torrent() {
        let info = BencodeValue::Dict(BTreeMap::from([
            (b"name".to_vec(), BencodeValue::Bytes(b"hello.txt".to_vec())),
            (b"length".to_vec(), BencodeValue::Int(11)),
            (b"piece length".to_vec(), BencodeValue::Int(16384)),
            (b"pieces".to_vec(), BencodeValue::Bytes(vec![0u8; 20])),
        ]));
        let torrent = BencodeValue::Dict(BTreeMap::from([(b"info".to_vec(), info)]));
        let parsed = TorrentFile::parse(&encode(&torrent)).expect("parse");
        assert_eq!(parsed.info.name, "hello.txt");
        assert_eq!(parsed.info.total_len, 11);
    }

    #[test]
    fn parses_announce_list() {
        let info = BencodeValue::Dict(BTreeMap::from([
            (b"name".to_vec(), BencodeValue::Bytes(b"a.bin".to_vec())),
            (b"length".to_vec(), BencodeValue::Int(1)),
            (b"piece length".to_vec(), BencodeValue::Int(16384)),
            (b"pieces".to_vec(), BencodeValue::Bytes(vec![0u8; 20])),
        ]));
        let torrent = BencodeValue::Dict(BTreeMap::from([
            (
                b"announce".to_vec(),
                BencodeValue::Bytes(b"http://primary/announce".to_vec()),
            ),
            (
                b"announce-list".to_vec(),
                BencodeValue::List(vec![
                    BencodeValue::List(vec![BencodeValue::Bytes(
                        b"udp://backup:1337/announce".to_vec(),
                    )]),
                    BencodeValue::List(vec![BencodeValue::Bytes(
                        b"https://secondary/announce".to_vec(),
                    )]),
                ]),
            ),
            (b"info".to_vec(), info),
        ]));
        let parsed = TorrentFile::parse(&encode(&torrent)).expect("parse");
        assert_eq!(parsed.trackers.len(), 3);
        assert!(parsed
            .trackers
            .iter()
            .any(|url| url.starts_with("udp://")));
    }

    #[test]
    fn roundtrips_signed_torrent() {
        let info = BencodeValue::Dict(BTreeMap::from([
            (b"name".to_vec(), BencodeValue::Bytes(b"signed.txt".to_vec())),
            (b"length".to_vec(), BencodeValue::Int(5)),
            (b"piece length".to_vec(), BencodeValue::Int(16384)),
            (b"pieces".to_vec(), BencodeValue::Bytes(vec![1u8; 20])),
        ]));
        let mut torrent = TorrentFile {
            announce: None,
            trackers: Vec::new(),
            web_seeds: Vec::new(),
            info: parse_info(&info).expect("info"),
            signature: None,
            info_dict_bytes: encode(&info),
        };
        let key = signing_key_from_seed(&[9u8; 32]);
        torrent.sign(&key);
        let encoded = torrent.to_bytes().expect("encode");
        let parsed = TorrentFile::parse(&encoded).expect("parse");
        assert!(parsed.signature.is_some());
    }

    #[test]
    fn rejects_unsigned_when_required() {
        let info = BencodeValue::Dict(BTreeMap::from([
            (b"name".to_vec(), BencodeValue::Bytes(b"x".to_vec())),
            (b"length".to_vec(), BencodeValue::Int(1)),
            (b"piece length".to_vec(), BencodeValue::Int(16384)),
            (b"pieces".to_vec(), BencodeValue::Bytes(vec![0u8; 20])),
        ]));
        let root = BencodeValue::Dict(BTreeMap::from([(b"info".to_vec(), info)]));
        let torrent = TorrentFile::from_bencode(&root).expect("parse");
        assert!(torrent.ensure_trusted(true, &[]).is_err());
        torrent.ensure_trusted(false, &[]).expect("optional");
    }
}