torrentdht 0.1.1

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

pub fn decode(input: &[u8]) -> Result<BencodeValue> {
    decode_with_limits(input, DecodeLimits::TORRENT_FILE)
}

pub fn decode_with_limits(input: &[u8], limits: DecodeLimits) -> Result<BencodeValue> {
    if input.len() > limits.max_bytes {
        return Err(Error::Bencode(format!(
            "input exceeds max {} bytes",
            limits.max_bytes
        )));
    }
    let mut items_left = limits.max_items;
    let (value, rest) = decode_one(input, limits, 0, &mut items_left)?;
    if !rest.is_empty() {
        return Err(Error::Bencode("trailing data after bencode value".into()));
    }
    Ok(value)
}

/// Decode one bencode value and return any trailing bytes (BEP 9 metadata Data).
pub fn decode_prefix(input: &[u8], limits: DecodeLimits) -> Result<(BencodeValue, &[u8])> {
    if input.len() > limits.max_bytes {
        return Err(Error::Bencode(format!(
            "input exceeds max {} bytes",
            limits.max_bytes
        )));
    }
    let mut items_left = limits.max_items;
    decode_one(input, limits, 0, &mut items_left)
}

fn decode_one<'a>(
    input: &'a [u8],
    limits: DecodeLimits,
    depth: usize,
    items_left: &mut usize,
) -> Result<(BencodeValue, &'a [u8])> {
    if depth > limits.max_depth {
        return Err(Error::Bencode("bencode max depth exceeded".into()));
    }
    if input.is_empty() {
        return Err(Error::Bencode("unexpected end of input".into()));
    }

    match input[0] {
        b'i' => decode_int(&input[1..]),
        b'l' => decode_list(&input[1..], limits, depth + 1, items_left),
        b'd' => decode_dict(&input[1..], limits, depth + 1, items_left),
        b'0'..=b'9' => decode_bytes(input),
        other => Err(Error::Bencode(format!("invalid bencode prefix: {other}"))),
    }
}

fn decode_int(input: &[u8]) -> Result<(BencodeValue, &[u8])> {
    let end = input
        .iter()
        .position(|&b| b == b'e')
        .ok_or_else(|| Error::Bencode("unterminated integer".into()))?;
    let digits = &input[..end];
    validate_canonical_int(digits)?;
    let text = std::str::from_utf8(digits)
        .map_err(|_| Error::Bencode("integer is not valid utf-8".into()))?;
    let value = text
        .parse::<i64>()
        .map_err(|_| Error::Bencode(format!("invalid integer: {text}")))?;
    Ok((BencodeValue::Int(value), &input[end + 1..]))
}

/// BEP 3 / common strict parsers: no leading zeros, no `-0`, at least one digit.
fn validate_canonical_int(digits: &[u8]) -> Result<()> {
    if digits.is_empty() {
        return Err(Error::Bencode("empty integer".into()));
    }
    let (signed, body) = if digits[0] == b'-' {
        if digits.len() == 1 {
            return Err(Error::Bencode("invalid integer: -".into()));
        }
        (true, &digits[1..])
    } else {
        (false, digits)
    };
    if body.is_empty() || !body.iter().all(|b| b.is_ascii_digit()) {
        return Err(Error::Bencode("integer contains non-digits".into()));
    }
    if body.len() > 1 && body[0] == b'0' {
        return Err(Error::Bencode("integer has leading zeros".into()));
    }
    if signed && body == b"0" {
        return Err(Error::Bencode("negative zero is not canonical".into()));
    }
    Ok(())
}

fn decode_bytes(input: &[u8]) -> Result<(BencodeValue, &[u8])> {
    let colon = input
        .iter()
        .position(|&b| b == b':')
        .ok_or_else(|| Error::Bencode("missing colon in byte string".into()))?;
    let len_str = std::str::from_utf8(&input[..colon])
        .map_err(|_| Error::Bencode("byte string length is not valid utf-8".into()))?;
    let len = len_str
        .parse::<usize>()
        .map_err(|_| Error::Bencode(format!("invalid byte string length: {len_str}")))?;
    let start = colon + 1;
    let end = start
        .checked_add(len)
        .ok_or_else(|| Error::Bencode("byte string length overflow".into()))?;
    if end > input.len() {
        return Err(Error::Bencode("byte string extends past input".into()));
    }
    Ok((
        BencodeValue::Bytes(input[start..end].to_vec()),
        &input[end..],
    ))
}

fn decode_list<'a>(
    input: &'a [u8],
    limits: DecodeLimits,
    depth: usize,
    items_left: &mut usize,
) -> Result<(BencodeValue, &'a [u8])> {
    let mut items = Vec::new();
    let mut rest = input;
    while !rest.is_empty() && rest[0] != b'e' {
        if *items_left == 0 {
            return Err(Error::Bencode("bencode exceeds global max items".into()));
        }
        *items_left -= 1;
        let (item, next) = decode_one(rest, limits, depth, items_left)?;
        items.push(item);
        rest = next;
    }
    if rest.is_empty() {
        return Err(Error::Bencode("unterminated list".into()));
    }
    Ok((BencodeValue::List(items), &rest[1..]))
}

fn decode_dict<'a>(
    input: &'a [u8],
    limits: DecodeLimits,
    depth: usize,
    items_left: &mut usize,
) -> Result<(BencodeValue, &'a [u8])> {
    let mut map = std::collections::BTreeMap::new();
    let mut rest = input;
    while !rest.is_empty() && rest[0] != b'e' {
        if *items_left == 0 {
            return Err(Error::Bencode("bencode exceeds global max items".into()));
        }
        *items_left -= 1;
        let (key_val, next) = decode_one(rest, limits, depth, items_left)?;
        let key = key_val
            .as_bytes()
            .ok_or_else(|| Error::Bencode("dict key must be a byte string".into()))?
            .to_vec();
        rest = next;
        let (value, next) = decode_one(rest, limits, depth, items_left)?;
        if map.contains_key(&key) {
            return Err(Error::Bencode(format!(
                "duplicate bencode dict key: {}",
                String::from_utf8_lossy(&key)
            )));
        }
        map.insert(key, value);
        rest = next;
    }
    if rest.is_empty() {
        return Err(Error::Bencode("unterminated dict".into()));
    }
    Ok((BencodeValue::Dict(map), &rest[1..]))
}

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

    #[test]
    fn decodes_nested_structure() {
        let value = decode(b"d8:announce18:http://example.come").expect("decode");
        assert_eq!(
            value.dict_get_str("announce").and_then(|v| v.as_bytes()),
            Some(b"http://example.com".as_ref())
        );
    }

    #[test]
    fn rejects_oversized_input() {
        let limits = DecodeLimits {
            max_depth: 8,
            max_bytes: 4,
            max_items: 16,
        };
        assert!(decode_with_limits(b"12345:hello", limits).is_err());
    }

    #[test]
    fn rejects_noncanonical_ints() {
        assert!(decode(b"i01e").is_err());
        assert!(decode(b"i-0e").is_err());
        assert!(decode(b"ie").is_err());
        assert_eq!(decode(b"i0e").expect("zero").as_int(), Some(0));
        assert_eq!(decode(b"i-1e").expect("neg").as_int(), Some(-1));
    }

    #[test]
    fn rejects_duplicate_dict_keys() {
        assert!(decode(b"d1:ai1e1:ai2ee").is_err());
    }

    #[test]
    fn global_item_budget_across_nesting() {
        let limits = DecodeLimits {
            max_depth: 8,
            max_bytes: 1024,
            max_items: 2,
        };
        // Outer dict (1) + key "a" is not an item charge for key decode... wait
        // Each dict entry charges 1, then value list charges items inside.
        // d1:ali1ei2eee = dict entry + list with 2 ints = 1 + 2 = 3 charges
        assert!(decode_with_limits(b"d1:ali1ei2eee", limits).is_err());
        assert!(decode_with_limits(b"li1ei2ee", limits).is_ok());
    }
}