use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use sha1::{Digest as _, Sha1};
use sha2::Sha256;
use crate::bencode::{encode, BencodeValue};
use crate::torrent::v2::{detect_meta_version, MetaVersion, V2Meta};
use crate::error::{Error, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InfoHash([u8; 20]);
impl InfoHash {
pub fn from_bytes(bytes: [u8; 20]) -> Self {
Self(bytes)
}
pub fn from_info_dict(info: &BencodeValue) -> Result<Self> {
let encoded = encode(info);
let digest = Sha1::digest(encoded);
let mut out = [0u8; 20];
out.copy_from_slice(&digest);
Ok(Self(out))
}
pub fn as_bytes(&self) -> &[u8; 20] {
&self.0
}
pub fn to_hex(&self) -> String {
self.0.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn from_hex(hex: &str) -> Result<Self> {
if hex.len() != 40 {
return Err(Error::Torrent("info-hash hex must be 40 characters".into()));
}
let mut out = [0u8; 20];
for (idx, chunk) in hex.as_bytes().chunks(2).enumerate() {
let part = std::str::from_utf8(chunk)
.map_err(|_| Error::Torrent("info-hash hex is not utf-8".into()))?;
out[idx] = u8::from_str_radix(part, 16)
.map_err(|_| Error::Torrent("info-hash hex has invalid digits".into()))?;
}
Ok(Self(out))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InfoHashV2([u8; 32]);
impl InfoHashV2 {
pub fn from_bytes(bytes: [u8; 32]) -> Self {
Self(bytes)
}
pub fn from_info_dict(info: &BencodeValue) -> Result<Self> {
Ok(Self::from_info_bytes(&encode(info)))
}
pub fn from_info_bytes(encoded: &[u8]) -> Self {
use sha2::Digest;
let digest = Sha256::digest(encoded);
let mut out = [0u8; 32];
out.copy_from_slice(&digest);
Self(out)
}
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
pub fn to_hex(&self) -> String {
self.0.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn truncate_to_v1(&self) -> InfoHash {
let mut out = [0u8; 20];
out.copy_from_slice(&self.0[..20]);
InfoHash::from_bytes(out)
}
pub fn from_hex(hex: &str) -> Result<Self> {
if hex.len() != 64 {
return Err(Error::Torrent(
"v2 info-hash hex must be 64 characters".into(),
));
}
let mut out = [0u8; 32];
for (idx, chunk) in hex.as_bytes().chunks(2).enumerate() {
let part = std::str::from_utf8(chunk)
.map_err(|_| Error::Torrent("v2 info-hash hex is not utf-8".into()))?;
out[idx] = u8::from_str_radix(part, 16)
.map_err(|_| Error::Torrent("v2 info-hash hex has invalid digits".into()))?;
}
Ok(Self(out))
}
pub fn to_btmh_multihash_hex(&self) -> String {
format!("1220{}", self.to_hex())
}
pub fn from_btmh_multihash_hex(raw: &str) -> Result<Self> {
let raw = raw.trim();
let lower = raw.to_ascii_lowercase();
let hex = lower
.strip_prefix("1220")
.ok_or_else(|| {
Error::Torrent(
"urn:btmh must use multihash sha2-256 (prefix 1220) followed by 64 hex chars"
.into(),
)
})?;
Self::from_hex(hex)
}
}
#[derive(Debug, Clone)]
pub struct TorrentInfo {
pub info_hash: InfoHash,
pub info_hash_v2: Option<InfoHashV2>,
pub name: String,
pub piece_length: u32,
pub pieces: Vec<[u8; 20]>,
pub files: Vec<(PathBuf, u64)>,
pub total_len: u64,
pub private: bool,
pub meta_version: MetaVersion,
pub v2: Option<V2Meta>,
}
impl TorrentInfo {
pub fn piece_count(&self) -> u32 {
self.pieces.len() as u32
}
pub fn piece_size(&self, index: u32) -> u32 {
let index = index as u64;
let start = index * self.piece_length as u64;
let remaining = self.total_len.saturating_sub(start);
remaining.min(self.piece_length as u64) as u32
}
}
pub fn parse_info(info: &BencodeValue) -> Result<TorrentInfo> {
let name = info
.dict_get_str("name")
.and_then(|v| v.as_bytes())
.and_then(|b| String::from_utf8(b.to_vec()).ok())
.ok_or_else(|| Error::Torrent("missing info.name".into()))?;
let piece_length_i = info
.dict_get_str("piece length")
.and_then(|v| v.as_int())
.ok_or_else(|| Error::Torrent("missing piece length".into()))?;
if piece_length_i <= 0 {
return Err(Error::Torrent("piece length must be positive".into()));
}
if piece_length_i > i64::from(crate::security::MAX_PIECE_LENGTH) {
return Err(Error::Torrent(format!(
"piece length {piece_length_i} exceeds maximum {}",
crate::security::MAX_PIECE_LENGTH
)));
}
let piece_length = piece_length_i as u32;
if piece_length < crate::security::MIN_PIECE_LENGTH {
return Err(Error::Torrent(format!(
"piece length {piece_length} below minimum {}",
crate::security::MIN_PIECE_LENGTH
)));
}
let pieces_raw = info.dict_get_str("pieces").and_then(|v| v.as_bytes());
let (files, total_len) = if let Some(length) = info.dict_get_str("length").and_then(|v| v.as_int())
{
if length < 0 {
return Err(Error::Torrent("negative file length".into()));
}
let relative = crate::security::sanitize_torrent_relative_path(&name)?;
(vec![(relative, length as u64)], length as u64)
} else {
parse_multi_file(info, &name)?
};
if total_len > crate::security::MAX_TORRENT_CONTENT_BYTES {
return Err(Error::Torrent(format!(
"torrent total length {total_len} exceeds maximum {}",
crate::security::MAX_TORRENT_CONTENT_BYTES
)));
}
let piece_count_guess = if total_len == 0 {
0
} else {
total_len.div_ceil(u64::from(piece_length)) as u32
};
let has_v1_pieces = pieces_raw.is_some_and(|raw| !raw.is_empty());
let meta_version = detect_meta_version(info, has_v1_pieces);
let pieces = if let Some(raw) = pieces_raw.filter(|raw| !raw.is_empty()) {
if !raw.len().is_multiple_of(20) {
return Err(Error::Torrent("pieces length is not a multiple of 20".into()));
}
let mut out = Vec::with_capacity(raw.len() / 20);
for chunk in raw.chunks_exact(20) {
let mut hash = [0u8; 20];
hash.copy_from_slice(chunk);
out.push(hash);
}
out
} else if meta_version != MetaVersion::V1 {
vec![[0u8; 20]; piece_count_guess as usize]
} else {
return Err(Error::Torrent("missing pieces or piece layers".into()));
};
if total_len == 0 {
if !pieces.is_empty() {
return Err(Error::Torrent(
"zero-length torrent must not declare piece hashes".into(),
));
}
} else if pieces.len() as u32 != piece_count_guess {
return Err(Error::Torrent(format!(
"pieces count {} does not match length/piece length (expected {piece_count_guess})",
pieces.len()
)));
}
let info_hash_v2 = if meta_version != MetaVersion::V1 {
Some(InfoHashV2::from_info_dict(info)?)
} else {
None
};
let info_hash = match meta_version {
MetaVersion::V2 => info_hash_v2
.expect("v2 hash")
.truncate_to_v1(),
_ => InfoHash::from_info_dict(info)?,
};
let private = info
.dict_get_str("private")
.and_then(|v| v.as_int())
.is_some_and(|v| v != 0);
Ok(TorrentInfo {
info_hash,
info_hash_v2,
name,
piece_length,
pieces,
files,
total_len,
private,
meta_version,
v2: None,
})
}
pub fn info_to_bencode(info: &TorrentInfo) -> Result<BencodeValue> {
let mut dict = BTreeMap::new();
dict.insert(
b"name".to_vec(),
BencodeValue::Bytes(info.name.as_bytes().to_vec()),
);
dict.insert(
b"piece length".to_vec(),
BencodeValue::Int(info.piece_length as i64),
);
let mut pieces_bytes = Vec::with_capacity(info.pieces.len() * 20);
for piece in &info.pieces {
pieces_bytes.extend_from_slice(piece);
}
if info.meta_version != MetaVersion::V2 {
dict.insert(b"pieces".to_vec(), BencodeValue::Bytes(pieces_bytes));
}
if is_single_file_layout(info) {
dict.insert(
b"length".to_vec(),
BencodeValue::Int(info.total_len as i64),
);
} else {
let files = info
.files
.iter()
.map(|(relative, length)| {
let path = file_path_components(relative, &info.name);
BencodeValue::Dict(BTreeMap::from([
(b"length".to_vec(), BencodeValue::Int(*length as i64)),
(b"path".to_vec(), BencodeValue::List(path)),
]))
})
.collect();
dict.insert(b"files".to_vec(), BencodeValue::List(files));
}
if info.meta_version != MetaVersion::V1 {
dict.insert(
b"meta version".to_vec(),
BencodeValue::Int(2),
);
if let Some(v2) = &info.v2 {
if !v2.files.is_empty() {
dict.insert(
b"file tree".to_vec(),
crate::torrent::v2::file_tree_to_bencode(&v2.files, &info.name)?,
);
}
}
}
if info.private {
dict.insert(b"private".to_vec(), BencodeValue::Int(1));
}
Ok(BencodeValue::Dict(dict))
}
fn is_single_file_layout(info: &TorrentInfo) -> bool {
info.files.len() == 1 && info.files[0].0.as_path() == Path::new(&info.name)
}
fn file_path_components(relative: &Path, torrent_name: &str) -> Vec<BencodeValue> {
relative
.strip_prefix(torrent_name)
.unwrap_or(relative)
.components()
.filter_map(|component| match component {
Component::Normal(part) => part
.to_str()
.map(|value| BencodeValue::Bytes(value.as_bytes().to_vec())),
_ => None,
})
.collect()
}
fn parse_multi_file(info: &BencodeValue, name: &str) -> Result<(Vec<(PathBuf, u64)>, u64)> {
let files_list = info
.dict_get_str("files")
.and_then(|v| v.as_list())
.ok_or_else(|| Error::Torrent("missing info.files".into()))?;
let mut files = Vec::with_capacity(files_list.len());
let mut total_len = 0u64;
for entry in files_list {
let length = entry
.dict_get_str("length")
.and_then(|v| v.as_int())
.ok_or_else(|| Error::Torrent("file entry missing length".into()))?;
if length < 0 {
return Err(Error::Torrent("negative file length".into()));
}
let length = length as u64;
if length > crate::security::MAX_TORRENT_CONTENT_BYTES {
return Err(Error::Torrent(format!(
"file length {length} exceeds maximum {}",
crate::security::MAX_TORRENT_CONTENT_BYTES
)));
}
let parts = entry
.dict_get_str("path")
.and_then(|v| v.as_list())
.ok_or_else(|| Error::Torrent("file entry missing path".into()))?
.iter()
.map(|part| {
part.as_bytes()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
.ok_or_else(|| Error::Torrent("invalid utf-8 in path".into()))
})
.collect::<Result<Vec<_>>>()?;
if parts.is_empty() {
return Err(Error::Torrent("file entry has empty path".into()));
}
let mut relative = PathBuf::from(name);
for part in parts {
relative.push(part);
}
let relative = crate::security::sanitize_torrent_relative_path(relative)?;
total_len = total_len
.checked_add(length)
.ok_or_else(|| Error::Torrent("torrent total length overflow".into()))?;
if total_len > crate::security::MAX_TORRENT_CONTENT_BYTES {
return Err(Error::Torrent(format!(
"torrent total length {total_len} exceeds maximum {}",
crate::security::MAX_TORRENT_CONTENT_BYTES
)));
}
files.push((relative, length));
}
Ok((files, total_len))
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn piece_size_for_tail() {
let info = TorrentInfo {
info_hash: InfoHash::from_bytes([0; 20]),
info_hash_v2: None,
name: "x".into(),
piece_length: 16384,
pieces: vec![[0; 20], [0; 20]],
files: vec![(PathBuf::from("x"), 20_000)],
total_len: 20_000,
private: false,
meta_version: MetaVersion::V1,
v2: None,
};
assert_eq!(info.piece_size(0), 16384);
assert_eq!(info.piece_size(1), 3616);
}
#[test]
fn parses_single_file_info() {
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 parsed = parse_info(&info).expect("parse");
assert_eq!(parsed.name, "hello.txt");
assert_eq!(parsed.total_len, 11);
assert!(!parsed.private);
}
#[test]
fn parses_private_flag() {
let info = BencodeValue::Dict(BTreeMap::from([
(b"name".to_vec(), BencodeValue::Bytes(b"private.bin".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])),
(b"private".to_vec(), BencodeValue::Int(1)),
]));
let parsed = parse_info(&info).expect("parse");
assert!(parsed.private);
}
#[test]
fn rejects_invalid_piece_length_and_mismatch() {
let zero = BencodeValue::Dict(BTreeMap::from([
(b"name".to_vec(), BencodeValue::Bytes(b"x".to_vec())),
(b"length".to_vec(), BencodeValue::Int(11)),
(b"piece length".to_vec(), BencodeValue::Int(0)),
(b"pieces".to_vec(), BencodeValue::Bytes(vec![0u8; 20])),
]));
assert!(parse_info(&zero).is_err());
let mismatch = BencodeValue::Dict(BTreeMap::from([
(b"name".to_vec(), BencodeValue::Bytes(b"x".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; 40])),
]));
assert!(parse_info(&mismatch).is_err());
}
}