use std::collections::BTreeMap;
use tracing::{debug, info};
use crate::bittorrent::bencode::codec::BencodeValue;
use crate::bittorrent::torrent::info_hash::InfoHash;
mod optional_fields;
mod path_validation;
#[derive(Debug, Clone)]
pub struct FileEntry {
pub length: u64,
pub path: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct V2FileEntry {
pub length: u64,
pub path: Vec<String>,
pub pieces_root: Option<[u8; 32]>,
}
#[derive(Debug, Clone)]
pub struct InfoDict {
pub name: String,
pub piece_length: u32,
pub pieces: Vec<[u8; 20]>,
pub length: Option<u64>,
pub files: Option<Vec<FileEntry>>,
pub private: Option<i64>,
pub meta_version: Option<u64>,
pub v2_files: Option<Vec<V2FileEntry>>,
pub pieces_root: Option<[u8; 32]>,
}
impl InfoDict {
pub fn validate_paths(&self) -> Result<(), String> {
path_validation::validate_components(std::slice::from_ref(&self.name))?;
if let Some(files) = &self.files {
for file in files {
path_validation::validate_components(&file.path)?;
}
}
if let Some(files) = &self.v2_files {
for file in files {
path_validation::validate_components(&file.path)?;
}
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct TorrentMeta {
pub announce: String,
pub announce_list: Vec<Vec<String>>,
pub info: InfoDict,
pub info_hash: InfoHash,
pub info_hash_v2: Option<[u8; 32]>,
pub piece_layers: BTreeMap<[u8; 32], Vec<[u8; 32]>>,
pub creation_date: Option<i64>,
pub comment: Option<String>,
pub created_by: Option<String>,
pub encoding: Option<String>,
pub web_seeds: Vec<String>,
pub nodes: Vec<(String, u16)>,
}
impl TorrentMeta {
pub fn network_info_hash(&self) -> [u8; 20] {
if self.info.meta_version == Some(2) && self.info.pieces.is_empty() {
self.info_hash_v2
.map(|hash| hash[..20].try_into().expect("SHA-256 hash is 32 bytes"))
.unwrap_or(self.info_hash.bytes)
} else {
self.info_hash.bytes
}
}
pub fn parse(data: &[u8]) -> Result<Self, String> {
Self::parse_with_info_bytes(data).map(|(meta, _)| meta)
}
pub fn parse_with_info_bytes(data: &[u8]) -> Result<(Self, Vec<u8>), String> {
info!("Starting torrent file parsing ({} bytes)", data.len());
let (root, _) =
BencodeValue::decode(data).map_err(|e| format!("Bencode decoding failed: {}", e))?;
let announce = root
.dict_get_str("announce")
.ok_or("Missing announce field")?
.to_string();
let announce_list = optional_fields::parse_announce_list(&root);
let info = root.dict_get(b"info").ok_or("Missing info dictionary")?;
let info_bytes = info.encode();
let info_hash = InfoHash::from_info_bytes(&info_bytes);
let meta_version = Self::parse_meta_version(info);
if meta_version.is_some_and(|version| version > 2) {
return Err(format!(
"unsupported BitTorrent metainfo version {}",
meta_version.unwrap_or_default()
));
}
let info_hash_v2 =
(meta_version == Some(2)).then(|| InfoHash::from_info_bytes_v2(&info_bytes));
debug!("info_hash: {}", info_hash.as_hex());
let info_dict = Self::parse_info_dict(info)?;
if info_dict.meta_version == Some(2) && !info_dict.pieces.is_empty() {
Self::validate_hybrid_layout(&info_dict)?;
}
let piece_layers = Self::parse_piece_layers(&root)?;
if info_dict.meta_version == Some(2) {
Self::validate_v2_piece_layers(&info_dict, &piece_layers)?;
}
let creation_date = root.dict_get_int("creation date");
let comment = root.dict_get_str("comment").map(|s| s.to_string());
let created_by = root.dict_get_str("created by").map(|s| s.to_string());
let encoding = root.dict_get_str("encoding").map(|s| s.to_string());
let web_seeds = optional_fields::parse_url_list(&root);
let nodes = optional_fields::parse_nodes(&root);
let total_size = Self::compute_total_size(&info_dict);
info!(
"Torrent parsing complete: name={}, pieces={}, size={}, web_seeds={}",
info_dict.name,
info_dict.pieces.len(),
total_size,
web_seeds.len()
);
Ok((
Self {
announce,
announce_list,
info: info_dict,
info_hash,
info_hash_v2,
piece_layers,
creation_date,
comment,
created_by,
encoding,
web_seeds,
nodes,
},
info_bytes,
))
}
fn parse_info_dict(info: &BencodeValue) -> Result<InfoDict, String> {
let dict = info.as_dict().ok_or("info is not a dictionary type")?;
let name = dict
.get(&b"name"[..])
.and_then(BencodeValue::as_bytes)
.map(path_validation::decode_component)
.unwrap_or_else(|| "unnamed".to_string());
let piece_length = dict
.get(&b"piece length"[..])
.and_then(|v| v.as_int())
.filter(|&n| n > 0 && n <= i32::MAX as i64)
.map(|n| n as u32)
.ok_or("Invalid or missing piece length")?;
let meta_version = Self::parse_meta_version(info);
if meta_version == Some(2)
&& (piece_length < crate::bittorrent::torrent::merkle::BLOCK_SIZE as u32
|| !piece_length.is_power_of_two())
{
return Err("BitTorrent v2 piece length must be a power of two >= 16 KiB".to_string());
}
let pieces = match dict.get(&b"pieces"[..]).and_then(|v| v.as_bytes()) {
Some(pieces_raw) => {
if pieces_raw.len() % 20 != 0 {
return Err(format!(
"pieces length ({}) is not a multiple of 20",
pieces_raw.len()
));
}
(0..pieces_raw.len() / 20)
.map(|i| {
let mut hash = [0u8; 20];
hash.copy_from_slice(&pieces_raw[i * 20..(i + 1) * 20]);
hash
})
.collect()
}
None if meta_version == Some(2) => Vec::new(),
None => return Err("Missing pieces field".to_string()),
};
let length = dict
.get(&b"length"[..])
.and_then(|v| v.as_int())
.map(|n| u64::try_from(n).map_err(|_| "file length must be non-negative"))
.transpose()?;
let files = if length.is_some() {
None
} else if dict.contains_key(&b"files"[..]) {
Some(Self::parse_files(dict)?)
} else {
None
};
let private = dict.get(&b"private"[..]).and_then(|v| v.as_int());
let pieces_root = Self::parse_hash32(dict.get(&b"pieces root"[..]), "pieces root")?;
let v2_files = if meta_version == Some(2) {
Some(Self::parse_file_tree(
dict.get(&b"file tree"[..])
.ok_or("BitTorrent v2 info dictionary missing file tree")?,
)?)
} else {
None
};
let info_dict = InfoDict {
name,
piece_length,
pieces,
length,
files,
private,
meta_version,
v2_files,
pieces_root,
};
info_dict.validate_paths()?;
Ok(info_dict)
}
fn parse_files(dict: &BTreeMap<Vec<u8>, BencodeValue>) -> Result<Vec<FileEntry>, String> {
let files_val = dict
.get(&b"files"[..])
.and_then(|v| v.as_list())
.ok_or("Multi-file mode missing files field")?;
if files_val.is_empty() {
return Err("files list is empty".to_string());
}
let mut entries = Vec::with_capacity(files_val.len());
for file in files_val {
let fd = file.as_dict().ok_or("file entry is not a dictionary")?;
let length = fd
.get(&b"length"[..])
.and_then(|v| v.as_int())
.ok_or("file missing length field")
.and_then(|n| u64::try_from(n).map_err(|_| "file length must be non-negative"))?;
let path_val = fd
.get(&b"path"[..])
.and_then(|v| v.as_list())
.ok_or("file missing path field")?;
let path: Vec<String> = path_val
.iter()
.map(|component| {
let bytes = component
.as_bytes()
.ok_or_else(|| "file path element is not a byte string".to_string())?;
Ok(path_validation::decode_component(bytes))
})
.collect::<Result<_, String>>()?;
if path.is_empty() {
return Err("file path is empty".to_string());
}
entries.push(FileEntry { length, path });
}
Ok(entries)
}
fn parse_meta_version(info: &BencodeValue) -> Option<u64> {
info.as_dict()
.and_then(|dict| dict.get(&b"meta version"[..]))
.and_then(|value| value.as_int())
.and_then(|value| u64::try_from(value).ok())
}
fn parse_hash32(value: Option<&BencodeValue>, field: &str) -> Result<Option<[u8; 32]>, String> {
let Some(value) = value else { return Ok(None) };
let bytes = value
.as_bytes()
.ok_or_else(|| format!("{field} must be a byte string"))?;
bytes
.try_into()
.map(Some)
.map_err(|_| format!("{field} must contain exactly 32 bytes"))
}
fn parse_file_tree(value: &BencodeValue) -> Result<Vec<V2FileEntry>, String> {
fn walk(
value: &BencodeValue,
path: &mut Vec<String>,
output: &mut Vec<V2FileEntry>,
) -> Result<(), String> {
let dict = value
.as_dict()
.ok_or("file tree node must be a dictionary")?;
for (name, child) in dict {
let name = path_validation::decode_component(name);
if name.is_empty() {
if path.is_empty() {
return Err("file tree root cannot be a file".to_string());
}
if dict.len() != 1 {
return Err("file tree file node cannot have siblings".to_string());
}
let leaf = child
.as_dict()
.ok_or("file tree leaf must be a dictionary")?;
let length = leaf
.get(&b"length"[..])
.and_then(|value| value.as_int())
.and_then(|value| u64::try_from(value).ok())
.ok_or("file tree leaf missing valid length")?;
let pieces_root =
TorrentMeta::parse_hash32(leaf.get(&b"pieces root"[..]), "pieces root")?;
if length > 0 && pieces_root.is_none() {
return Err("non-empty file tree leaf missing pieces root".to_string());
}
output.push(V2FileEntry {
length,
path: path.clone(),
pieces_root,
});
} else {
path.push(name);
walk(child, path, output)?;
path.pop();
}
}
Ok(())
}
let mut output = Vec::new();
walk(value, &mut Vec::new(), &mut output)?;
if output.is_empty() {
return Err("file tree contains no files".to_string());
}
Ok(output)
}
fn parse_piece_layers(
root: &BencodeValue,
) -> Result<BTreeMap<[u8; 32], Vec<[u8; 32]>>, String> {
let Some(value) = root.dict_get(b"piece layers") else {
return Ok(BTreeMap::new());
};
let dict = value.as_dict().ok_or("piece layers must be a dictionary")?;
let mut layers = BTreeMap::new();
for (root_hash, layer) in dict {
let root_hash: [u8; 32] = root_hash
.as_slice()
.try_into()
.map_err(|_| "piece layer key must contain exactly 32 bytes")?;
let layer = layer
.as_bytes()
.ok_or("piece layer must be a byte string")?;
if layer.len() % 32 != 0 {
return Err("piece layer length must be a multiple of 32 bytes".to_string());
}
let hashes = layer
.as_chunks::<32>()
.0
.iter()
.map(|chunk| {
let mut hash = [0u8; 32];
hash.copy_from_slice(chunk);
hash
})
.collect();
layers.insert(root_hash, hashes);
}
Ok(layers)
}
fn validate_v2_piece_layers(
info: &InfoDict,
layers: &BTreeMap<[u8; 32], Vec<[u8; 32]>>,
) -> Result<(), String> {
let piece_length = info.piece_length as u64;
for file in info.v2_files.as_deref().unwrap_or_default() {
let piece_count = file.length.div_ceil(piece_length) as usize;
let Some(root) = file.pieces_root else {
if file.length > 0 {
return Err("non-empty v2 file is missing its pieces root".to_string());
}
continue;
};
let Some(layer) = layers.get(&root) else {
if file.length > piece_length {
return Err("v2 file is missing its piece layer".to_string());
}
continue;
};
if file.length <= piece_length {
return Err(
"v2 piece layer is present for a file that does not need one".to_string(),
);
}
if layer.len() != piece_count {
return Err("v2 piece layer has the wrong number of hashes".to_string());
}
if !crate::bittorrent::torrent::merkle::verify_piece_layer(&root, layer) {
return Err("v2 piece layer does not match pieces root".to_string());
}
}
Ok(())
}
fn validate_hybrid_layout(info: &InfoDict) -> Result<(), String> {
let Some(v2_files) = info.v2_files.as_deref() else {
return Err("hybrid torrent is missing its v2 file tree".to_string());
};
let Some(v1_files) = info.files.as_deref() else {
if let Some(length) = info.length {
let v2_length = v2_files.iter().map(|file| file.length).sum::<u64>();
if v2_files.len() != 1 || v2_length != length {
return Err("hybrid single-file layouts do not match".to_string());
}
return Ok(());
}
return Err("hybrid torrent is missing its v1 file list".to_string());
};
let piece_length = info.piece_length as u64;
let mut v1_index = 0usize;
let mut v2_offset = 0u64;
for v2 in v2_files {
let aligned_offset = if v2.length == 0 {
v2_offset
} else {
v2_offset
.div_ceil(piece_length)
.checked_mul(piece_length)
.ok_or("hybrid v2 address space overflows")?
};
let expected_padding = aligned_offset - v2_offset;
let mut actual_padding = 0u64;
while v1_index < v1_files.len()
&& v1_files[v1_index]
.path
.first()
.is_some_and(|component| component == ".pad")
{
actual_padding = actual_padding
.checked_add(v1_files[v1_index].length)
.ok_or("hybrid v1 address space overflows")?;
if actual_padding > expected_padding {
return Err("hybrid padding files do not match v2 alignment gaps".to_string());
}
v1_index += 1;
}
if actual_padding != expected_padding || v1_index >= v1_files.len() {
return Err("hybrid padding files do not match v2 alignment gaps".to_string());
}
let v1 = &v1_files[v1_index];
if v1.path != v2.path || v1.length != v2.length {
return Err("hybrid v1/v2 file order or lengths do not match".to_string());
}
v1_index += 1;
v2_offset = aligned_offset
.checked_add(v2.length)
.ok_or("hybrid v2 address space overflows")?;
}
if v1_index != v1_files.len() {
return Err("hybrid v1/v2 file order or lengths do not match".to_string());
}
let v1_space = v1_files.iter().try_fold(0u64, |total, file| {
total
.checked_add(file.length)
.ok_or("hybrid v1 address space overflows")
})?;
if v1_space != v2_offset {
return Err("hybrid v1/v2 piece address spaces do not match".to_string());
}
if info.pieces.len() != v1_space.div_ceil(piece_length) as usize {
return Err("hybrid v1 pieces do not cover the aligned address space".to_string());
}
Ok(())
}
fn compute_total_size(info: &InfoDict) -> u64 {
if let Some(len) = info.length {
len
} else if let Some(ref files) = info.files {
files
.iter()
.filter(|file| {
!file
.path
.first()
.is_some_and(|component| component == ".pad")
})
.map(|f| f.length)
.sum()
} else if let Some(ref files) = info.v2_files {
files.iter().map(|f| f.length).sum()
} else {
0
}
}
pub fn is_private(&self) -> bool {
self.info.private.unwrap_or(0) != 0
}
pub fn is_single_file(&self) -> bool {
self.info.length.is_some()
|| self
.info
.v2_files
.as_ref()
.is_some_and(|files| files.len() == 1)
}
pub fn num_pieces(&self) -> usize {
if self.info.meta_version == Some(2) {
self.piece_space_size()
.div_ceil(self.info.piece_length as u64) as usize
} else {
self.info.pieces.len()
}
}
pub fn piece_space_size(&self) -> u64 {
if self.info.meta_version != Some(2) {
return self.total_size();
}
let piece_length = self.info.piece_length as u64;
self.info
.v2_files
.as_deref()
.unwrap_or_default()
.iter()
.fold(0u64, |offset, file| {
if file.length == 0 {
offset
} else {
offset.div_ceil(piece_length) * piece_length + file.length
}
})
}
pub fn total_size(&self) -> u64 {
if let Some(len) = self.info.length {
len
} else if let Some(ref files) = self.info.files {
files.iter().map(|f| f.length).sum()
} else if let Some(ref files) = self.info.v2_files {
files.iter().map(|f| f.length).sum()
} else {
0
}
}
}
#[cfg(test)]
#[path = "parser/tests.rs"]
mod tests;