irontide-core 0.165.0

Core types for BitTorrent: hashes, metainfo, magnets, piece arithmetic
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
use bytes::Bytes;
use serde::de::{self, Deserializer};
use serde::{Deserialize, Serialize};

use crate::error::Error;
use crate::hash::Id20;

/// Deserialize a list of raw 20-byte binary strings into `Vec<Id20>`, silently
/// dropping entries that are not exactly 20 bytes.
///
/// BEP 38 `similar` is a list of info hashes (raw 20-byte binary).  Rather than
/// rejecting the entire torrent when a single entry has the wrong length, we
/// keep only the valid ones — a robustness-over-strictness choice consistent
/// with Postel's law.
fn deserialize_similar<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<Id20>, D::Error> {
    struct SimilarVisitor;

    impl<'de> de::Visitor<'de> for SimilarVisitor {
        type Value = Vec<Id20>;

        fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("a list of 20-byte binary strings")
        }

        fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<Id20>, A::Error> {
            let mut hashes = Vec::new();
            // Each element is a raw byte string; accept via serde_bytes.
            while let Some(bytes) = seq.next_element::<serde_bytes::ByteBuf>()? {
                if let Ok(id) = Id20::from_bytes(bytes.as_ref()) {
                    hashes.push(id);
                }
                // Silently drop entries that are not exactly 20 bytes.
            }
            Ok(hashes)
        }
    }

    deserializer.deserialize_seq(SimilarVisitor)
}

/// Wrapper for `url-list` that handles both a single string and a list of strings.
#[derive(Debug, Clone, Default)]
pub struct UrlList(pub Vec<String>);

impl<'de> Deserialize<'de> for UrlList {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct UrlListVisitor;

        impl<'de> de::Visitor<'de> for UrlListVisitor {
            type Value = UrlList;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a string or list of strings")
            }

            fn visit_str<E: de::Error>(self, v: &str) -> Result<UrlList, E> {
                Ok(UrlList(vec![v.to_owned()]))
            }

            fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<UrlList, E> {
                let s = std::str::from_utf8(v).map_err(de::Error::custom)?;
                Ok(UrlList(vec![s.to_owned()]))
            }

            fn visit_seq<A: de::SeqAccess<'de>>(self, mut seq: A) -> Result<UrlList, A::Error> {
                let mut urls = Vec::new();
                while let Some(url) = seq.next_element::<String>()? {
                    urls.push(url);
                }
                Ok(UrlList(urls))
            }
        }

        deserializer.deserialize_any(UrlListVisitor)
    }
}

/// Parsed .torrent file (BEP 3 metainfo, v1).
#[derive(Debug, Clone)]
pub struct TorrentMetaV1 {
    /// The info hash (SHA1 of the raw "info" dict bytes).
    pub info_hash: Id20,
    /// Primary announce URL.
    pub announce: Option<String>,
    /// Announce list (BEP 12) — list of tracker tiers.
    pub announce_list: Option<Vec<Vec<String>>>,
    /// Comment.
    pub comment: Option<String>,
    /// Created by.
    pub created_by: Option<String>,
    /// Creation date (unix timestamp).
    pub creation_date: Option<i64>,
    /// Info dictionary.
    pub info: InfoDict,
    /// BEP 19 web seed URLs (GetRight-style).
    pub url_list: Vec<String>,
    /// BEP 17 HTTP seed URLs (Hoffman-style).
    pub httpseeds: Vec<String>,
    /// Raw info dict bytes for BEP 9 metadata serving.
    pub info_bytes: Option<Bytes>,
    /// PEM-encoded SSL CA certificate from the info dict, if present.
    pub ssl_cert: Option<Vec<u8>>,
}

/// The "info" dictionary from a .torrent file.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct InfoDict {
    /// Suggested file/directory name.
    pub name: String,
    /// Piece length in bytes.
    #[serde(rename = "piece length")]
    pub piece_length: u64,
    /// Concatenated SHA1 hashes of each piece (20 bytes each).
    #[serde(with = "serde_bytes")]
    pub pieces: Vec<u8>,
    /// Length in bytes (single-file mode).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub length: Option<u64>,
    /// Files (multi-file mode).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub files: Option<Vec<FileEntry>>,
    /// Private flag.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub private: Option<i64>,
    /// Source tag (private tracker identification).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub source: Option<String>,
    /// BEP 35 / SSL torrent: PEM-encoded X.509 CA certificate.
    /// When present, all peer connections must use TLS with certs chaining to this CA.
    #[serde(rename = "ssl-cert", skip_serializing_if = "Option::is_none", default)]
    #[serde(with = "serde_bytes")]
    pub ssl_cert: Option<Vec<u8>>,
    /// BEP 38: info hashes of similar/related torrents (raw 20-byte binary strings).
    ///
    /// Entries that are not exactly 20 bytes are silently dropped during parsing.
    #[serde(
        default,
        skip_serializing_if = "Vec::is_empty",
        deserialize_with = "deserialize_similar"
    )]
    pub similar: Vec<Id20>,
    /// BEP 38: collection names this torrent belongs to.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub collections: Vec<String>,
}

/// A file entry in multi-file mode.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FileEntry {
    /// File length in bytes.
    pub length: u64,
    /// Path components (e.g., ["dir", "file.txt"]).
    pub path: Vec<String>,
    /// BEP 47 file attributes ("p"=pad, "h"=hidden, "x"=executable, "l"=symlink).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub attr: Option<String>,
    /// File modification time (unix timestamp).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub mtime: Option<i64>,
    /// Symlink target path components.
    #[serde(
        rename = "symlink path",
        skip_serializing_if = "Option::is_none",
        default
    )]
    pub symlink_path: Option<Vec<String>>,
}

/// High-level file info (unified from single-file and multi-file modes).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileInfo {
    /// Relative path components.
    pub path: Vec<String>,
    /// File length in bytes.
    pub length: u64,
}

/// Raw top-level torrent structure for serde deserialization.
#[derive(Deserialize)]
struct RawTorrent {
    announce: Option<String>,
    #[serde(rename = "announce-list")]
    announce_list: Option<Vec<Vec<String>>>,
    comment: Option<String>,
    #[serde(rename = "created by")]
    created_by: Option<String>,
    #[serde(rename = "creation date")]
    creation_date: Option<i64>,
    info: InfoDict,
    /// BEP 19: web seed URL(s) — single string or list.
    #[serde(rename = "url-list", default)]
    url_list: UrlList,
    /// BEP 17: HTTP seed URLs.
    #[serde(default)]
    httpseeds: Vec<String>,
}

/// Parse a .torrent file from raw bytes.
///
/// Computes the info-hash by finding the raw byte span of the "info" key
/// and SHA1-hashing it directly (not the re-serialized form).
pub fn torrent_from_bytes(data: &[u8]) -> Result<TorrentMetaV1, Error> {
    // Step 1: Find the raw info dict span for hashing
    let info_span = irontide_bencode::find_dict_key_span(data, "info")?;
    let info_hash = crate::sha1(&data[info_span.clone()]);
    let info_raw = Bytes::copy_from_slice(&data[info_span]);

    // Step 2: Deserialize the full structure
    let raw: RawTorrent = irontide_bencode::from_bytes(data)?;

    // Step 3: Validate the info dict
    validate_info(&raw.info)?;

    let ssl_cert = raw.info.ssl_cert.clone();

    Ok(TorrentMetaV1 {
        info_hash,
        announce: raw.announce,
        announce_list: raw.announce_list,
        comment: raw.comment,
        created_by: raw.created_by,
        creation_date: raw.creation_date,
        info: raw.info,
        url_list: raw.url_list.0,
        httpseeds: raw.httpseeds,
        info_bytes: Some(info_raw),
        ssl_cert,
    })
}

fn validate_info(info: &InfoDict) -> Result<(), Error> {
    if info.piece_length == 0 {
        return Err(Error::InvalidTorrent("piece length is 0".into()));
    }

    if !info.pieces.len().is_multiple_of(20) {
        return Err(Error::InvalidTorrent(format!(
            "pieces length {} is not a multiple of 20",
            info.pieces.len()
        )));
    }

    if info.length.is_none() && info.files.is_none() {
        return Err(Error::InvalidTorrent(
            "neither 'length' nor 'files' present".into(),
        ));
    }

    if info.length.is_some() && info.files.is_some() {
        return Err(Error::InvalidTorrent(
            "both 'length' and 'files' present".into(),
        ));
    }

    Ok(())
}

impl InfoDict {
    /// Total size of all files in bytes.
    pub fn total_length(&self) -> u64 {
        if let Some(length) = self.length {
            length
        } else if let Some(ref files) = self.files {
            files.iter().map(|f| f.length).sum()
        } else {
            0
        }
    }

    /// Number of pieces.
    pub fn num_pieces(&self) -> usize {
        self.pieces.len() / 20
    }

    /// Get the SHA1 hash for a specific piece.
    pub fn piece_hash(&self, index: usize) -> Option<Id20> {
        let start = index * 20;
        if start + 20 > self.pieces.len() {
            return None;
        }
        let mut hash = [0u8; 20];
        hash.copy_from_slice(&self.pieces[start..start + 20]);
        Some(Id20(hash))
    }

    /// Get file info in a unified format.
    pub fn files(&self) -> Vec<FileInfo> {
        if let Some(length) = self.length {
            vec![FileInfo {
                path: vec![self.name.clone()],
                length,
            }]
        } else if let Some(ref files) = self.files {
            files
                .iter()
                .map(|f| {
                    let mut path = vec![self.name.clone()];
                    path.extend(f.path.clone());
                    FileInfo {
                        path,
                        length: f.length,
                    }
                })
                .collect()
        } else {
            vec![]
        }
    }
}

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

    /// Build a minimal torrent bencoded dict with extra keys sorted correctly.
    ///
    /// `before_info` contains keys that sort before "info" (e.g., "httpseeds").
    /// `after_info` contains keys that sort after "info" (e.g., "url-list").
    fn make_torrent_bytes_sorted(before_info: &[u8], after_info: &[u8]) -> Vec<u8> {
        // Minimal info dict: name, piece length, pieces (20 zero bytes), length
        let info = b"d6:lengthi1048576e4:name4:test12:piece lengthi262144e6:pieces20:\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00e";
        let mut buf = Vec::new();
        buf.push(b'd');
        buf.extend_from_slice(before_info);
        buf.extend_from_slice(b"4:info");
        buf.extend_from_slice(info);
        buf.extend_from_slice(after_info);
        buf.push(b'e');
        buf
    }

    #[test]
    fn url_list_single_string() {
        // url-list sorts after info
        let data = make_torrent_bytes_sorted(b"", b"8:url-list24:http://example.com/files");
        let meta = torrent_from_bytes(&data).unwrap();
        assert_eq!(meta.url_list, vec!["http://example.com/files"]);
    }

    #[test]
    fn url_list_multiple() {
        let data = make_torrent_bytes_sorted(
            b"",
            b"8:url-listl24:http://example.com/files26:http://mirror.example.com/e",
        );
        let meta = torrent_from_bytes(&data).unwrap();
        assert_eq!(meta.url_list.len(), 2);
        assert_eq!(meta.url_list[0], "http://example.com/files");
        assert_eq!(meta.url_list[1], "http://mirror.example.com/");
    }

    #[test]
    fn url_list_absent() {
        let data = make_torrent_bytes_sorted(b"", b"");
        let meta = torrent_from_bytes(&data).unwrap();
        assert!(meta.url_list.is_empty());
    }

    #[test]
    fn httpseeds_present() {
        // httpseeds sorts before info
        let data = make_torrent_bytes_sorted(b"9:httpseedsl28:http://seed.example.com/seede", b"");
        let meta = torrent_from_bytes(&data).unwrap();
        assert_eq!(meta.httpseeds, vec!["http://seed.example.com/seed"]);
    }

    #[test]
    fn httpseeds_absent() {
        let data = make_torrent_bytes_sorted(b"", b"");
        let meta = torrent_from_bytes(&data).unwrap();
        assert!(meta.httpseeds.is_empty());
    }

    #[test]
    fn torrent_from_bytes_stores_raw_info_bytes() {
        let data = make_torrent_bytes_sorted(b"", b"");
        let meta = torrent_from_bytes(&data).unwrap();
        assert!(meta.info_bytes.is_some());
        let info_bytes = meta.info_bytes.unwrap();
        // Re-hashing the stored bytes should produce the same info hash
        let rehash = crate::sha1(&info_bytes);
        assert_eq!(rehash, meta.info_hash);
    }

    #[test]
    fn ssl_cert_parsed_from_info_dict() {
        // Build a torrent with ssl-cert in the info dict.
        let cert_pem = b"-----BEGIN CERTIFICATE-----\nMIIBtest\n-----END CERTIFICATE-----\n";
        let cert_len = cert_pem.len();

        // Minimal info dict with ssl-cert inserted (keys must be sorted)
        let mut info = Vec::new();
        info.extend_from_slice(b"d");
        info.extend_from_slice(b"6:lengthi1048576e");
        info.extend_from_slice(b"4:name4:test");
        info.extend_from_slice(b"12:piece lengthi262144e");
        info.extend_from_slice(b"6:pieces20:");
        info.extend_from_slice(&[0u8; 20]);
        info.extend_from_slice(format!("8:ssl-cert{}:", cert_len).as_bytes());
        info.extend_from_slice(cert_pem);
        info.extend_from_slice(b"e");

        let mut torrent = Vec::new();
        torrent.extend_from_slice(b"d4:info");
        torrent.extend_from_slice(&info);
        torrent.extend_from_slice(b"e");

        let meta = torrent_from_bytes(&torrent).unwrap();
        assert!(meta.ssl_cert.is_some());
        assert_eq!(meta.ssl_cert.as_deref().unwrap(), cert_pem);
        assert_eq!(meta.info.ssl_cert.as_deref().unwrap(), cert_pem);
    }

    #[test]
    fn ssl_cert_absent_by_default() {
        let data = make_torrent_bytes_sorted(b"", b"");
        let meta = torrent_from_bytes(&data).unwrap();
        assert!(meta.ssl_cert.is_none());
        assert!(meta.info.ssl_cert.is_none());
    }

    /// Build a minimal info dict with optional `similar` and `collections` entries,
    /// wrapped in an outer torrent dict.  Keys are kept in bencode-sorted order.
    fn make_torrent_with_bep38(similar: Option<&[u8]>, collections: Option<&[u8]>) -> Vec<u8> {
        let mut info = Vec::new();
        info.extend_from_slice(b"d");
        // "collections" < "length" — insert first if present.
        if let Some(c) = collections {
            info.extend_from_slice(b"11:collections");
            info.extend_from_slice(c);
        }
        info.extend_from_slice(b"6:lengthi1048576e");
        info.extend_from_slice(b"4:name4:test");
        info.extend_from_slice(b"12:piece lengthi262144e");
        info.extend_from_slice(b"6:pieces20:");
        info.extend_from_slice(&[0u8; 20]);
        // "similar" > "pieces" and < "source"/"ssl-cert"
        if let Some(s) = similar {
            info.extend_from_slice(b"7:similar");
            info.extend_from_slice(s);
        }
        info.extend_from_slice(b"e");

        let mut torrent = Vec::new();
        torrent.extend_from_slice(b"d4:info");
        torrent.extend_from_slice(&info);
        torrent.extend_from_slice(b"e");
        torrent
    }

    #[test]
    fn parse_similar_torrents_from_info() {
        let hash_a = [0xAAu8; 20];
        let hash_b = [0xBBu8; 20];

        // Build bencode list: l20:<hash_a>20:<hash_b>e
        let mut similar_list = Vec::new();
        similar_list.extend_from_slice(b"l");
        similar_list.extend_from_slice(b"20:");
        similar_list.extend_from_slice(&hash_a);
        similar_list.extend_from_slice(b"20:");
        similar_list.extend_from_slice(&hash_b);
        similar_list.extend_from_slice(b"e");

        let data = make_torrent_with_bep38(Some(&similar_list), None);
        let meta = torrent_from_bytes(&data).expect("parse should succeed");

        assert_eq!(meta.info.similar.len(), 2);
        assert_eq!(meta.info.similar[0], Id20(hash_a));
        assert_eq!(meta.info.similar[1], Id20(hash_b));
    }

    #[test]
    fn parse_collections_from_info() {
        // Build bencode list: l6:movies6:sci-fie
        let collections_list = b"l6:movies6:sci-fie";

        let data = make_torrent_with_bep38(None, Some(collections_list));
        let meta = torrent_from_bytes(&data).expect("parse should succeed");

        assert_eq!(meta.info.collections.len(), 2);
        assert_eq!(meta.info.collections[0], "movies");
        assert_eq!(meta.info.collections[1], "sci-fi");
    }

    #[test]
    fn similar_empty_when_absent() {
        let data = make_torrent_bytes_sorted(b"", b"");
        let meta = torrent_from_bytes(&data).expect("parse should succeed");
        assert!(meta.info.similar.is_empty());
        assert!(meta.info.collections.is_empty());
    }

    #[test]
    fn similar_ignores_wrong_length_hashes() {
        let valid_hash = [0xCCu8; 20];
        let too_short = [0xDDu8; 19];
        let too_long = [0xEEu8; 21];

        // Build bencode list with mixed entries: 19-byte, 20-byte valid, 21-byte
        let mut similar_list = Vec::new();
        similar_list.extend_from_slice(b"l");
        // 19 bytes — invalid
        similar_list.extend_from_slice(b"19:");
        similar_list.extend_from_slice(&too_short);
        // 20 bytes — valid
        similar_list.extend_from_slice(b"20:");
        similar_list.extend_from_slice(&valid_hash);
        // 21 bytes — invalid
        similar_list.extend_from_slice(b"21:");
        similar_list.extend_from_slice(&too_long);
        similar_list.extend_from_slice(b"e");

        let data = make_torrent_with_bep38(Some(&similar_list), None);
        let meta = torrent_from_bytes(&data).expect("parse should succeed");

        // Only the 20-byte entry survives.
        assert_eq!(meta.info.similar.len(), 1);
        assert_eq!(meta.info.similar[0], Id20(valid_hash));
    }
}