use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use crate::bencode::BencodeValue;
use crate::error::{Error, Result};
use crate::piece::merkle::{
build_piece_layers, parse_piece_layer_hashes, pieces_root_from_layer, verify_pieces_root,
MERKLE_HASH_LEN,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MetaVersion {
V1,
V2,
Hybrid,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct V2FileMeta {
pub path: PathBuf,
pub length: u64,
pub pieces_root: [u8; 32],
pub piece_hashes: Vec<[u8; 32]>,
}
#[derive(Debug, Clone)]
pub struct V2Meta {
pub files: Vec<V2FileMeta>,
pub piece_hashes: Vec<[u8; 32]>,
pub pieces_root: [u8; 32],
}
pub fn detect_meta_version(info: &BencodeValue, has_v1_pieces: bool) -> MetaVersion {
let version = info
.dict_get_str("meta version")
.and_then(|v| v.as_int())
.unwrap_or(1);
match version {
v if v >= 2 && has_v1_pieces => MetaVersion::Hybrid,
v if v >= 2 => MetaVersion::V2,
_ => MetaVersion::V1,
}
}
pub fn is_pad_path(path: &Path) -> bool {
path.components().any(|c| matches!(c, Component::Normal(p) if p == ".pad"))
}
pub fn v2_file_from_bytes(
path: PathBuf,
data: &[u8],
piece_length: u32,
) -> V2FileMeta {
let piece_length = piece_length.max(1) as usize;
if data.is_empty() {
return V2FileMeta {
path,
length: 0,
pieces_root: [0u8; 32],
piece_hashes: Vec::new(),
};
}
let mut piece_hashes = Vec::new();
for chunk in data.chunks(piece_length) {
piece_hashes.push(crate::piece::piece_hash_from_data(
chunk,
crate::piece::MERKLE_BLOCK_SIZE,
));
}
let pieces_root = pieces_root_from_layer(&piece_hashes);
V2FileMeta {
path,
length: data.len() as u64,
pieces_root,
piece_hashes,
}
}
pub fn v2_from_files(files: Vec<V2FileMeta>) -> V2Meta {
let mut flat = Vec::new();
for file in &files {
flat.extend_from_slice(&file.piece_hashes);
}
let legacy_root = files
.iter()
.find(|f| f.length > 0)
.map(|f| f.pieces_root)
.unwrap_or([0u8; 32]);
V2Meta {
files,
piece_hashes: flat,
pieces_root: legacy_root,
}
}
pub fn v2_from_piece_hashes(piece_hashes: Vec<[u8; 32]>) -> V2Meta {
let pieces_root = pieces_root_from_layer(&piece_hashes);
let files = if piece_hashes.is_empty() {
Vec::new()
} else {
vec![V2FileMeta {
path: PathBuf::from("content"),
length: 0,
pieces_root,
piece_hashes: piece_hashes.clone(),
}]
};
V2Meta {
files,
piece_hashes,
pieces_root,
}
}
pub fn parse_piece_layers_map(
root: &BencodeValue,
) -> Result<BTreeMap<[u8; 32], Vec<[u8; 32]>>> {
let Some(dict) = root
.dict_get(b"piece layers".as_ref())
.and_then(|v| v.as_dict())
else {
return Ok(BTreeMap::new());
};
let mut out = BTreeMap::new();
for (root_key, raw) in dict {
if root_key.len() != MERKLE_HASH_LEN {
return Err(Error::Torrent(
"piece layers key must be a 32-byte pieces root".into(),
));
}
let raw = raw
.as_bytes()
.ok_or_else(|| Error::Torrent("piece layers value must be bytes".into()))?;
if raw.is_empty() || !raw.len().is_multiple_of(MERKLE_HASH_LEN) {
return Err(Error::Torrent("invalid v2 piece layers length".into()));
}
let piece_count = (raw.len() / MERKLE_HASH_LEN) as u32;
let mut pieces_root = [0u8; 32];
pieces_root.copy_from_slice(root_key);
if !verify_pieces_root(raw, piece_count, &pieces_root) {
return Err(Error::Torrent(
"invalid v2 piece layers merkle root".into(),
));
}
let piece_hashes = parse_piece_layer_hashes(raw, piece_count)
.ok_or_else(|| Error::Torrent("invalid v2 piece layers length".into()))?;
out.insert(pieces_root, piece_hashes);
}
Ok(out)
}
pub fn parse_piece_layers_dict(
root: &BencodeValue,
piece_count: u32,
) -> Result<Option<V2Meta>> {
let map = parse_piece_layers_map(root)?;
if map.is_empty() {
return Ok(None);
}
let (pieces_root, piece_hashes) = map.into_iter().next().expect("non-empty");
if piece_hashes.len() as u32 != piece_count && piece_count > 0 {
return Ok(Some(V2Meta {
files: vec![V2FileMeta {
path: PathBuf::from("content"),
length: 0,
pieces_root,
piece_hashes: piece_hashes.clone(),
}],
piece_hashes,
pieces_root,
}));
}
Ok(Some(V2Meta {
files: vec![V2FileMeta {
path: PathBuf::from("content"),
length: 0,
pieces_root,
piece_hashes: piece_hashes.clone(),
}],
piece_hashes,
pieces_root,
}))
}
pub fn piece_layers_to_bencode(v2: &V2Meta) -> BencodeValue {
let mut dict = BTreeMap::new();
for file in &v2.files {
if file.piece_hashes.len() <= 1 {
continue;
}
dict.insert(
file.pieces_root.to_vec(),
BencodeValue::Bytes(build_piece_layers(&file.piece_hashes)),
);
}
if dict.is_empty() && v2.piece_hashes.len() > 1 {
dict.insert(
v2.pieces_root.to_vec(),
BencodeValue::Bytes(build_piece_layers(&v2.piece_hashes)),
);
}
BencodeValue::Dict(dict)
}
pub fn file_tree_to_bencode(files: &[V2FileMeta], torrent_name: &str) -> Result<BencodeValue> {
let mut root: BTreeMap<Vec<u8>, BencodeValue> = BTreeMap::new();
for file in files {
if is_pad_path(&file.path) {
continue;
}
let components = path_components_for_tree(&file.path, torrent_name)?;
if components.is_empty() {
return Err(Error::Torrent("file tree path is empty".into()));
}
insert_file_tree_leaf(&mut root, &components, file)?;
}
Ok(BencodeValue::Dict(root))
}
fn path_components_for_tree(relative: &Path, torrent_name: &str) -> Result<Vec<Vec<u8>>> {
let stripped = relative
.strip_prefix(torrent_name)
.unwrap_or(relative);
let mut parts = Vec::new();
if stripped.as_os_str().is_empty() || relative == Path::new(torrent_name) {
parts.push(torrent_name.as_bytes().to_vec());
return Ok(parts);
}
if relative.starts_with(torrent_name) {
parts.push(torrent_name.as_bytes().to_vec());
}
for component in stripped.components() {
match component {
Component::Normal(part) => {
let s = part
.to_str()
.ok_or_else(|| Error::Torrent("file tree path is not utf-8".into()))?;
if s == "." || s == ".." {
return Err(Error::Torrent(
"file tree path must not contain . or ..".into(),
));
}
parts.push(s.as_bytes().to_vec());
}
_ => {
return Err(Error::Torrent("invalid file tree path component".into()));
}
}
}
Ok(parts)
}
fn insert_file_tree_leaf(
node: &mut BTreeMap<Vec<u8>, BencodeValue>,
components: &[Vec<u8>],
file: &V2FileMeta,
) -> Result<()> {
let (head, rest) = components
.split_first()
.ok_or_else(|| Error::Torrent("file tree path is empty".into()))?;
if rest.is_empty() {
let mut props = BTreeMap::new();
props.insert(b"length".to_vec(), BencodeValue::Int(file.length as i64));
if file.length > 0 {
props.insert(
b"pieces root".to_vec(),
BencodeValue::Bytes(file.pieces_root.to_vec()),
);
}
let leaf = BencodeValue::Dict(BTreeMap::from([(
Vec::new(),
BencodeValue::Dict(props),
)]));
if node.contains_key(head) {
return Err(Error::Torrent("duplicate file tree path".into()));
}
node.insert(head.clone(), leaf);
return Ok(());
}
let entry = node.entry(head.clone()).or_insert_with(|| {
BencodeValue::Dict(BTreeMap::new())
});
let BencodeValue::Dict(child) = entry else {
return Err(Error::Torrent(
"file tree path conflicts with a file entry".into(),
));
};
if child.contains_key(&Vec::<u8>::new()) {
return Err(Error::Torrent(
"file tree path conflicts with a file entry".into(),
));
}
insert_file_tree_leaf(child, rest, file)
}
pub fn parse_file_tree(
info: &BencodeValue,
torrent_name: &str,
) -> Result<Option<Vec<V2FileMeta>>> {
let Some(tree) = info.dict_get_str("file tree") else {
return Ok(None);
};
let dict = tree
.as_dict()
.ok_or_else(|| Error::Torrent("file tree must be a dict".into()))?;
if dict.contains_key(&Vec::<u8>::new()) {
return Err(Error::Torrent(
"file tree root must not be a file entry".into(),
));
}
let mut files = Vec::new();
walk_file_tree(dict, PathBuf::new(), torrent_name, &mut files)?;
if files.is_empty() {
return Err(Error::Torrent("file tree has no files".into()));
}
Ok(Some(files))
}
fn walk_file_tree(
node: &BTreeMap<Vec<u8>, BencodeValue>,
prefix: PathBuf,
torrent_name: &str,
out: &mut Vec<V2FileMeta>,
) -> Result<()> {
for (key, value) in node {
if key.is_empty() {
return Err(Error::Torrent(
"file properties must not appear as directory siblings".into(),
));
}
let name = String::from_utf8(key.clone())
.map_err(|_| Error::Torrent("file tree key is not utf-8".into()))?;
if name == "." || name == ".." {
return Err(Error::Torrent(
"file tree path must not contain . or ..".into(),
));
}
let child_path = if prefix.as_os_str().is_empty() {
PathBuf::from(&name)
} else {
prefix.join(&name)
};
let dict = value
.as_dict()
.ok_or_else(|| Error::Torrent("file tree entry must be a dict".into()))?;
if let Some(props) = dict.get(&Vec::<u8>::new()) {
if dict.len() != 1 {
return Err(Error::Torrent(
"file entry must not have sibling keys beside \"\"".into(),
));
}
let props = props
.as_dict()
.ok_or_else(|| Error::Torrent("file properties must be a dict".into()))?;
let length = props
.get(b"length".as_ref())
.and_then(|v| v.as_int())
.ok_or_else(|| Error::Torrent("file tree entry missing length".into()))?;
if length < 0 {
return Err(Error::Torrent("negative file tree length".into()));
}
let length = length as u64;
let mut pieces_root = [0u8; 32];
if length > 0 {
let root = props
.get(b"pieces root".as_ref())
.and_then(|v| v.as_bytes())
.ok_or_else(|| Error::Torrent("non-empty file missing pieces root".into()))?;
if root.len() != MERKLE_HASH_LEN {
return Err(Error::Torrent(
"pieces root must be 32 bytes".into(),
));
}
pieces_root.copy_from_slice(root);
}
let path = if child_path.starts_with(torrent_name) {
child_path
} else {
PathBuf::from(torrent_name).join(child_path)
};
let path = crate::security::sanitize_torrent_relative_path(path)?;
out.push(V2FileMeta {
path,
length,
pieces_root,
piece_hashes: Vec::new(),
});
} else {
walk_file_tree(dict, child_path, torrent_name, out)?;
}
}
Ok(())
}
pub fn attach_piece_layers(
mut files: Vec<V2FileMeta>,
layers: &BTreeMap<[u8; 32], Vec<[u8; 32]>>,
piece_length: u32,
) -> Result<V2Meta> {
for file in &mut files {
if file.length == 0 {
continue;
}
let expected = file.length.div_ceil(u64::from(piece_length.max(1))) as usize;
if expected > 1 {
let hashes = layers.get(&file.pieces_root).ok_or_else(|| {
Error::Torrent(format!(
"piece layers missing for file {}",
file.path.display()
))
})?;
if hashes.len() != expected {
return Err(Error::Torrent(format!(
"piece layers count {} != expected {expected} for {}",
hashes.len(),
file.path.display()
)));
}
if pieces_root_from_layer(hashes) != file.pieces_root {
return Err(Error::Torrent(format!(
"piece layers root mismatch for {}",
file.path.display()
)));
}
file.piece_hashes = hashes.clone();
} else {
if layers.contains_key(&file.pieces_root) {
return Err(Error::Torrent(format!(
"piece layers must not be present for small file {}",
file.path.display()
)));
}
file.piece_hashes = vec![file.pieces_root];
}
}
Ok(v2_from_files(files))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::piece::{piece_hash_from_data, MERKLE_BLOCK_SIZE};
use crate::piece::merkle::build_piece_layers;
#[test]
fn detects_hybrid_meta_version() {
let info = BencodeValue::Dict(BTreeMap::from([(
b"meta version".to_vec(),
BencodeValue::Int(2),
)]));
assert_eq!(detect_meta_version(&info, true), MetaVersion::Hybrid);
assert_eq!(detect_meta_version(&info, false), MetaVersion::V2);
}
#[test]
fn parses_v2_piece_layers_two_pieces() {
let data_a = vec![0u8; MERKLE_BLOCK_SIZE];
let data_b = vec![1u8; MERKLE_BLOCK_SIZE];
let a = piece_hash_from_data(&data_a, MERKLE_BLOCK_SIZE);
let b = piece_hash_from_data(&data_b, MERKLE_BLOCK_SIZE);
let v2 = v2_from_piece_hashes(vec![a, b]);
let root = BencodeValue::Dict(BTreeMap::from([(
b"piece layers".to_vec(),
piece_layers_to_bencode(&v2),
)]));
let meta = parse_piece_layers_dict(&root, 2).expect("parse");
let meta = meta.expect("some");
assert_eq!(meta.piece_hashes.len(), 2);
assert_eq!(meta.piece_hashes[0], a);
assert_eq!(meta.piece_hashes[1], b);
assert_eq!(meta.pieces_root, v2.pieces_root);
assert_eq!(build_piece_layers(&meta.piece_hashes).len(), 64);
}
#[test]
fn file_tree_roundtrip_single_file() {
let data = vec![7u8; MERKLE_BLOCK_SIZE * 2];
let file = v2_file_from_bytes(PathBuf::from("hello.bin"), &data, MERKLE_BLOCK_SIZE as u32);
let tree = file_tree_to_bencode(std::slice::from_ref(&file), "hello.bin").expect("tree");
let info = BencodeValue::Dict(BTreeMap::from([(b"file tree".to_vec(), tree)]));
let parsed = parse_file_tree(&info, "hello.bin")
.expect("parse")
.expect("some");
assert_eq!(parsed.len(), 1);
assert_eq!(parsed[0].length, data.len() as u64);
assert_eq!(parsed[0].pieces_root, file.pieces_root);
}
#[test]
fn pad_path_detection() {
assert!(is_pad_path(Path::new("demo/.pad/1024")));
assert!(!is_pad_path(Path::new("demo/file.txt")));
}
}