torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
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()
    }

    /// Parse a 40-character hex info-hash (case-insensitive).
    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))
    }
}

/// BEP 52 v2 info-hash: SHA2-256 of the bencoded `info` dictionary (32 bytes).
#[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()
    }

    /// Truncate to 20 bytes for v2-only peer wire / DHT identity (BEP 52).
    pub fn truncate_to_v1(&self) -> InfoHash {
        let mut out = [0u8; 20];
        out.copy_from_slice(&self.0[..20]);
        InfoHash::from_bytes(out)
    }

    /// Parse a 64-character hex SHA-256 digest.
    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))
    }

    /// Multihash hex for magnet `xt=urn:btmh:` (sha2-256 / 32-byte → `1220` + 64 hex).
    pub fn to_btmh_multihash_hex(&self) -> String {
        format!("1220{}", self.to_hex())
    }

    /// Parse `1220` + 64-hex multihash (case-insensitive), as used in `urn:btmh:`.
    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,
    /// Present for hybrid / pure-v2 torrents (SHA2-256 of info dict).
    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,
    /// BEP 27: when true, do not announce to public DHT.
    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 {
        // Pure v2: v1 `pieces` absent; layer hashes live outside `info` (BEP 52).
        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);
    }
    // Pure v2 omits v1 `pieces`; hybrid and v1 emit them.
    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)?,
                );
            }
        }
    }
    // BEP 52: `piece layers` lives on the torrent root, not inside `info`.
    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());
    }
}