irontide-tracker 0.165.0

BitTorrent tracker client: HTTP and UDP announce/scrape
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
use std::collections::HashMap;

use serde::Deserialize;

use irontide_core::Id20;

use crate::compact::{parse_compact_peers, parse_compact_peers6};
use crate::error::{Error, Result};
use crate::{AnnounceEvent, AnnounceRequest, AnnounceResponse, ScrapeInfo};

/// HTTP tracker client (BEP 3).
#[derive(Clone)]
pub struct HttpTracker {
    client: reqwest::Client,
}

/// Raw HTTP announce response (bencode).
#[derive(Debug, Clone)]
pub struct HttpAnnounceResponse {
    /// Common announce response data (interval, peers, etc.).
    pub response: AnnounceResponse,
    /// Tracker ID (some trackers return this for subsequent requests).
    pub tracker_id: Option<String>,
    /// Warning message from tracker.
    pub warning: Option<String>,
}

/// Raw bencode response from HTTP tracker.
#[derive(Deserialize)]
struct RawHttpResponse {
    interval: u32,
    #[serde(default)]
    complete: Option<u32>,
    #[serde(default)]
    incomplete: Option<u32>,
    #[serde(with = "serde_bytes")]
    peers: Vec<u8>,
    /// Compact IPv6 peers (BEP 7): 18 bytes each (16 IP + 2 port).
    #[serde(with = "serde_bytes", default)]
    peers6: Vec<u8>,
    #[serde(default, rename = "failure reason")]
    failure_reason: Option<String>,
    #[serde(default, rename = "warning message")]
    warning_message: Option<String>,
    #[serde(default, rename = "tracker id")]
    tracker_id: Option<String>,
}

impl HttpTracker {
    /// Creates a new HTTP tracker client with default settings.
    pub fn new() -> Self {
        HttpTracker {
            client: reqwest::Client::builder()
                .user_agent("Torrent/0.60.0")
                .build()
                .expect("failed to build HTTP client"),
        }
    }

    /// Create an HTTP tracker client for anonymous mode.
    ///
    /// Uses an empty user-agent string to avoid identifying the client software.
    pub fn with_anonymous() -> Self {
        HttpTracker {
            client: reqwest::Client::builder()
                .user_agent("")
                .build()
                .expect("failed to build HTTP client"),
        }
    }

    /// Create an HTTP tracker client with an optional proxy.
    ///
    /// When `proxy_url` is provided (e.g. `"socks5://host:port"`), all
    /// HTTP requests are routed through it.
    pub fn with_proxy(proxy_url: Option<&str>) -> Self {
        let mut builder = reqwest::Client::builder().user_agent("Torrent/0.60.0");
        if let Some(url) = proxy_url
            && let Ok(proxy) = reqwest::Proxy::all(url)
        {
            builder = builder.proxy(proxy);
        }
        HttpTracker {
            client: builder.build().expect("failed to build HTTP client"),
        }
    }

    /// Create an HTTP tracker client with URL security features.
    ///
    /// When `ssrf_mitigation` is enabled, a custom redirect policy blocks
    /// redirects from global (public) URLs to private/loopback IP addresses.
    /// When `validate_tls` is false, TLS certificate validation is disabled.
    pub fn with_security(
        proxy_url: Option<&str>,
        validate_tls: bool,
        ssrf_mitigation: bool,
    ) -> Self {
        let mut builder = reqwest::Client::builder().user_agent("Torrent/0.60.0");

        if ssrf_mitigation {
            let policy = reqwest::redirect::Policy::custom(|attempt| {
                if attempt.previous().len() >= 10 {
                    return attempt.error(std::io::Error::other("too many redirects"));
                }

                let original = &attempt.previous()[0];
                let redirect = attempt.url();

                // Check if the original URL was on a global (non-local) address.
                let orig_local = match original.host() {
                    Some(url::Host::Ipv4(ip)) => is_private_ipv4(ip),
                    // IPv6: loopback-only; ULA/link-local caught by url_guard
                    // in irontide-session (crate boundary prevents reuse).
                    Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
                    Some(url::Host::Domain(d)) => d == "localhost",
                    None => false,
                };

                if !orig_local {
                    let redirect_local = match redirect.host() {
                        Some(url::Host::Ipv4(ip)) => is_private_ipv4(ip),
                        Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
                        Some(url::Host::Domain(d)) => d == "localhost",
                        None => false,
                    };

                    if redirect_local {
                        return attempt.error(std::io::Error::other(
                            "redirect from public to private IP blocked (SSRF)",
                        ));
                    }
                }

                attempt.follow()
            });
            builder = builder.redirect(policy);
        }

        if !validate_tls {
            builder = builder.danger_accept_invalid_certs(true);
        }

        if let Some(url) = proxy_url
            && let Ok(proxy) = reqwest::Proxy::all(url)
        {
            builder = builder.proxy(proxy);
        }

        HttpTracker {
            client: builder.build().expect("failed to build HTTP client"),
        }
    }

    /// Build the announce URL with query parameters.
    pub fn build_announce_url(base_url: &str, req: &AnnounceRequest) -> Result<String> {
        let mut url = base_url.to_string();

        // URL-encode the info_hash and peer_id as raw bytes
        let info_hash_encoded = url_encode_bytes(req.info_hash.as_bytes());
        let peer_id_encoded = url_encode_bytes(req.peer_id.as_bytes());

        let separator = if url.contains('?') { '&' } else { '?' };

        url.push(separator);
        url.push_str(&format!(
            "info_hash={info_hash_encoded}&peer_id={peer_id_encoded}&port={}&uploaded={}&downloaded={}&left={}&compact=1",
            req.port, req.uploaded, req.downloaded, req.left
        ));

        match req.event {
            AnnounceEvent::None => {}
            AnnounceEvent::Started => url.push_str("&event=started"),
            AnnounceEvent::Completed => url.push_str("&event=completed"),
            AnnounceEvent::Stopped => url.push_str("&event=stopped"),
        }

        if let Some(n) = req.num_want {
            url.push_str(&format!("&numwant={n}"));
        }

        if let Some(ref dest) = req.i2p_destination {
            url.push_str("&i2p=");
            url.push_str(dest.trim_end_matches('='));
        }

        Ok(url)
    }

    /// Send an announce request to an HTTP tracker.
    pub async fn announce(
        &self,
        base_url: &str,
        req: &AnnounceRequest,
    ) -> Result<HttpAnnounceResponse> {
        let url = Self::build_announce_url(base_url, req)?;

        let response = self.client.get(&url).send().await?.bytes().await?;

        let raw: RawHttpResponse = irontide_bencode::from_bytes(&response)?;

        if let Some(failure) = raw.failure_reason {
            return Err(Error::TrackerError(failure));
        }

        let mut peers = parse_compact_peers(&raw.peers)?;

        // Merge IPv6 peers from peers6 key (BEP 7)
        if let Ok(peers6) = parse_compact_peers6(&raw.peers6) {
            peers.extend(peers6);
        }

        Ok(HttpAnnounceResponse {
            response: AnnounceResponse {
                interval: raw.interval,
                seeders: raw.complete,
                leechers: raw.incomplete,
                peers,
            },
            tracker_id: raw.tracker_id,
            warning: raw.warning_message,
        })
    }
}

/// HTTP scrape response containing per-torrent stats.
#[derive(Debug, Clone)]
pub struct HttpScrapeResponse {
    /// Per-torrent scrape statistics keyed by info hash.
    pub files: HashMap<Id20, ScrapeInfo>,
}

impl HttpTracker {
    /// Build a scrape URL from an announce URL and a list of info_hashes.
    pub fn build_scrape_url(announce_url: &str, info_hashes: &[Id20]) -> Result<String> {
        let base = crate::announce_url_to_scrape(announce_url)
            .ok_or_else(|| Error::InvalidUrl("no 'announce' in URL to convert to scrape".into()))?;
        let mut url = base;
        for (i, hash) in info_hashes.iter().enumerate() {
            let encoded = url_encode_bytes(hash.as_bytes());
            url.push(if i == 0 { '?' } else { '&' });
            url.push_str("info_hash=");
            url.push_str(&encoded);
        }
        Ok(url)
    }

    /// Send a scrape request to an HTTP tracker.
    pub async fn scrape(
        &self,
        announce_url: &str,
        info_hashes: &[Id20],
    ) -> Result<HttpScrapeResponse> {
        let url = Self::build_scrape_url(announce_url, info_hashes)?;

        let response = self.client.get(&url).send().await?.bytes().await?;

        // Parse using BencodeValue since keys are raw 20-byte hashes
        let value: irontide_bencode::BencodeValue = irontide_bencode::from_bytes(&response)?;
        let root = value
            .as_dict()
            .ok_or_else(|| Error::InvalidResponse("scrape response is not a dict".into()))?;

        let files_val = root
            .get(b"files".as_slice())
            .and_then(|v| v.as_dict())
            .ok_or_else(|| Error::InvalidResponse("scrape response missing 'files' dict".into()))?;

        let mut files = HashMap::new();
        for (key, val) in files_val {
            if key.len() != 20 {
                continue;
            }
            let hash = Id20::from_bytes(key).map_err(|_| {
                Error::InvalidResponse("invalid info_hash in scrape response".into())
            })?;
            let entry = val
                .as_dict()
                .ok_or_else(|| Error::InvalidResponse("scrape file entry is not a dict".into()))?;

            let complete = entry
                .get(b"complete".as_slice())
                .and_then(|v| v.as_int())
                .unwrap_or(0) as u32;
            let incomplete = entry
                .get(b"incomplete".as_slice())
                .and_then(|v| v.as_int())
                .unwrap_or(0) as u32;
            let downloaded = entry
                .get(b"downloaded".as_slice())
                .and_then(|v| v.as_int())
                .unwrap_or(0) as u32;

            files.insert(
                hash,
                ScrapeInfo {
                    complete,
                    incomplete,
                    downloaded,
                },
            );
        }

        Ok(HttpScrapeResponse { files })
    }
}

impl Default for HttpTracker {
    fn default() -> Self {
        Self::new()
    }
}

/// Returns `true` if the IPv4 address is loopback, private (RFC 1918), or link-local.
fn is_private_ipv4(ip: std::net::Ipv4Addr) -> bool {
    ip.is_loopback() || ip.is_private() || ip.is_link_local()
}

/// URL-encode raw bytes (percent-encoding).
fn url_encode_bytes(bytes: &[u8]) -> String {
    let mut encoded = String::with_capacity(bytes.len() * 3);
    for &b in bytes {
        match b {
            b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'.' | b'-' | b'_' | b'~' => {
                encoded.push(b as char);
            }
            _ => {
                encoded.push_str(&format!("%{b:02X}"));
            }
        }
    }
    encoded
}

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

    #[test]
    fn build_announce_url_basic() {
        let req = AnnounceRequest {
            info_hash: Id20::ZERO,
            peer_id: Id20::ZERO,
            port: 6881,
            uploaded: 0,
            downloaded: 0,
            left: 1000,
            event: AnnounceEvent::Started,
            num_want: Some(50),
            compact: true,
            i2p_destination: None,
        };

        let url =
            HttpTracker::build_announce_url("http://tracker.example.com/announce", &req).unwrap();

        assert!(url.starts_with("http://tracker.example.com/announce?"));
        assert!(url.contains("info_hash="));
        assert!(url.contains("port=6881"));
        assert!(url.contains("event=started"));
        assert!(url.contains("numwant=50"));
        assert!(url.contains("compact=1"));
    }

    #[test]
    fn build_scrape_url_basic() {
        let hash = Id20::ZERO;
        let url =
            HttpTracker::build_scrape_url("http://tracker.example.com/announce", &[hash]).unwrap();
        assert!(url.starts_with("http://tracker.example.com/scrape?info_hash="));
    }

    #[test]
    fn build_scrape_url_no_announce_in_url() {
        let hash = Id20::ZERO;
        let result = HttpTracker::build_scrape_url("http://tracker.example.com/track", &[hash]);
        assert!(result.is_err());
    }

    #[test]
    fn url_encode_bytes_simple() {
        assert_eq!(url_encode_bytes(b"abc"), "abc");
        assert_eq!(url_encode_bytes(&[0xFF, 0x00]), "%FF%00");
    }

    #[test]
    fn url_encode_preserves_unreserved() {
        let unreserved = b"abcXYZ019.-_~";
        let encoded = url_encode_bytes(unreserved);
        assert_eq!(encoded, "abcXYZ019.-_~");
    }

    #[test]
    fn parse_response_with_peers6() {
        use std::net::Ipv6Addr;

        // Build a raw bencode response with both peers and peers6
        let mut peers = Vec::new();
        peers.extend_from_slice(&[192, 168, 1, 1, 0x1A, 0xE1]); // 192.168.1.1:6881

        let ip6: Ipv6Addr = "2001:db8::1".parse().unwrap();
        let mut peers6 = Vec::new();
        peers6.extend_from_slice(&ip6.octets());
        peers6.extend_from_slice(&8080u16.to_be_bytes());

        let raw = RawHttpResponse {
            interval: 1800,
            complete: Some(10),
            incomplete: Some(5),
            peers,
            peers6,
            failure_reason: None,
            warning_message: None,
            tracker_id: None,
        };

        // Manually parse as the announce method would
        let mut result = parse_compact_peers(&raw.peers).unwrap();
        if !raw.peers6.is_empty() {
            if let Ok(v6) = parse_compact_peers6(&raw.peers6) {
                result.extend(v6);
            }
        }

        assert_eq!(result.len(), 2);
        assert_eq!(result[0].to_string(), "192.168.1.1:6881");
        assert_eq!(
            result[1],
            "[2001:db8::1]:8080"
                .parse::<std::net::SocketAddr>()
                .unwrap()
        );
    }

    #[test]
    fn http_tracker_anonymous_builds() {
        let tracker = HttpTracker::with_anonymous();
        drop(tracker);
    }

    #[test]
    fn http_tracker_with_security_builds() {
        // Basic smoke test: with_security with SSRF mitigation enabled builds.
        let tracker = HttpTracker::with_security(None, true, true);
        drop(tracker);
    }

    #[test]
    fn http_tracker_with_security_no_tls_validation() {
        // Builds with TLS validation disabled and SSRF mitigation off.
        let tracker = HttpTracker::with_security(None, false, false);
        drop(tracker);
    }

    #[test]
    fn build_announce_url_includes_i2p_destination() {
        // Use I2P-specific Base64 chars (`-`, `~`) and padding to exercise stripping
        let req = AnnounceRequest {
            info_hash: Id20::ZERO,
            peer_id: Id20::ZERO,
            port: 6881,
            uploaded: 0,
            downloaded: 0,
            left: 1000,
            event: AnnounceEvent::None,
            num_want: None,
            compact: true,
            i2p_destination: Some("AAAA-BBB~CCC==".into()),
        };

        let url =
            HttpTracker::build_announce_url("http://tracker.example.com/announce", &req).unwrap();

        assert!(
            url.contains("&i2p=AAAA-BBB~CCC"),
            "URL should contain I2P destination with padding stripped: {url}"
        );
        // Verify padding was removed: no `=` should appear after the destination
        let i2p_start = url.find("&i2p=").unwrap() + 5;
        let i2p_value = &url[i2p_start..];
        assert!(
            !i2p_value.contains('='),
            "I2P destination should not contain '=' padding in URL: {i2p_value}"
        );
    }

    #[test]
    fn build_announce_url_omits_i2p_when_none() {
        let req = AnnounceRequest {
            info_hash: Id20::ZERO,
            peer_id: Id20::ZERO,
            port: 6881,
            uploaded: 0,
            downloaded: 0,
            left: 1000,
            event: AnnounceEvent::None,
            num_want: None,
            compact: true,
            i2p_destination: None,
        };

        let url =
            HttpTracker::build_announce_url("http://tracker.example.com/announce", &req).unwrap();

        assert!(
            !url.contains("&i2p="),
            "URL should not contain &i2p= when None: {url}"
        );
    }
}