aria2-protocol 0.3.10

Multi-protocol networking stack for aria2-rust: HTTP/HTTPS client, FTP/SFTP, full BitTorrent (DHT/PEX/MSE), and Metalink V3/V4 parser
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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
use super::parse::parse_tracker_source_list;
use super::source_fetcher::tracker_source_origin;
use super::*;

struct ConcurrencyRecordingFetcher {
    active: AtomicUsize,
    max_active: AtomicUsize,
}

impl TrackerSourceFetcher for ConcurrencyRecordingFetcher {
    fn fetch<'a>(
        &'a self,
        _source: &'a str,
        _timeout: Duration,
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
        Box::pin(async move {
            let active = self.active.fetch_add(1, Ordering::AcqRel) + 1;
            self.max_active.fetch_max(active, Ordering::AcqRel);
            tokio::time::sleep(Duration::from_millis(20)).await;
            self.active.fetch_sub(1, Ordering::AcqRel);
            Ok("udp://tracker.test:6969/announce".to_string())
        })
    }
}

#[tokio::test]
async fn source_fetch_concurrency_limit_bounds_refresh_requests() {
    let fetcher = Arc::new(ConcurrencyRecordingFetcher {
        active: AtomicUsize::new(0),
        max_active: AtomicUsize::new(0),
    });
    let catalog = PublicTrackerList::new_with_config_and_fetcher(
        TrackerCatalogConfig {
            enabled: true,
            sources: (0..6).map(|index| format!("source-{index}")).collect(),
            update_interval: DEFAULT_TRACKER_UPDATE_INTERVAL,
        },
        fetcher.clone(),
    );

    catalog.set_source_fetch_concurrency_limit(2);
    assert_eq!(catalog.refresh().await.unwrap(), 1);
    assert_eq!(fetcher.max_active.load(Ordering::Acquire), 2);
    catalog.set_source_fetch_concurrency_limit(usize::MAX);
    assert_eq!(
        catalog.source_fetch_concurrency_limit(),
        MAX_TRACKER_SOURCE_CONCURRENCY
    );
}

#[tokio::test]
async fn source_request_timeout_covers_the_complete_response_body() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let server = tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut request = [0; 1024];
        let _ = stream.read(&mut request).await.unwrap();
        stream
                .write_all(
                    b"HTTP/1.1 200 OK\r\nContent-Length: 64\r\nConnection: close\r\n\r\nhttp://slow.test/announce\n",
                )
                .await
                .unwrap();
        stream.flush().await.unwrap();
        tokio::time::sleep(Duration::from_millis(200)).await;
    });

    let catalog = PublicTrackerList::new();
    assert_eq!(
        catalog.source_request_timeout().await,
        DEFAULT_TRACKER_SOURCE_TIMEOUT
    );
    catalog
        .set_source_request_timeout(Duration::from_millis(40))
        .await;
    let error = catalog
        .fetch_and_update(&format!("http://{address}/trackers.txt"))
        .await
        .expect_err("an incomplete response body should time out");
    assert!(error.contains("timed out"), "unexpected error: {error}");
    server.await.unwrap();

    catalog.set_source_request_timeout(Duration::ZERO).await;
    assert_eq!(
        catalog.source_request_timeout().await,
        DEFAULT_TRACKER_SOURCE_TIMEOUT
    );
}

#[tokio::test]
async fn default_source_fetcher_rejects_response_bodies_over_the_byte_limit() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    let server = tokio::spawn(async move {
        let (mut stream, _) = listener.accept().await.unwrap();
        let mut request = [0; 1024];
        let _ = stream.read(&mut request).await.unwrap();
        let body_len = MAX_TRACKER_SOURCE_BYTES + 1;
        stream
            .write_all(
                format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {body_len}\r\nConnection: close\r\n\r\n"
                )
                .as_bytes(),
            )
            .await
            .unwrap();
        let line = b"udp://tracker.test:6969/announce\n";
        let mut remaining = body_len;
        let mut chunk = vec![b'#'; 8192];
        while remaining > 0 {
            let count = remaining.min(chunk.len());
            if remaining == count && count >= line.len() {
                let start = count - line.len();
                chunk[start..count].copy_from_slice(line);
            }
            stream.write_all(&chunk[..count]).await.unwrap();
            remaining -= count;
        }
    });

    let catalog = PublicTrackerList::new();
    let error = catalog
        .fetch_and_update(&format!("http://{address}/trackers.txt"))
        .await
        .expect_err("oversized source response must be rejected");
    assert!(error.contains("exceeds the"), "unexpected error: {error}");
    server.await.unwrap();
}

#[tokio::test]
async fn source_body_reader_accepts_the_exact_byte_limit() {
    let chunks = futures::stream::iter([Ok::<_, std::convert::Infallible>(Bytes::from(
        vec![b'x'; MAX_TRACKER_SOURCE_BYTES],
    ))]);

    let body = read_tracker_source_body(chunks)
        .await
        .expect("the exact response-body limit should be accepted");

    assert_eq!(body.len(), MAX_TRACKER_SOURCE_BYTES);
}

struct OversizedBodyFetcher;

impl TrackerSourceFetcher for OversizedBodyFetcher {
    fn fetch<'a>(
        &'a self,
        _source: &'a str,
        _timeout: Duration,
    ) -> Pin<Box<dyn Future<Output = Result<String, String>> + Send + 'a>> {
        Box::pin(async {
            Ok(format!(
                "udp://tracker.test:6969/announce\n{}",
                "#".repeat(MAX_TRACKER_SOURCE_BYTES)
            ))
        })
    }
}

#[tokio::test]
async fn custom_source_fetcher_output_is_checked_against_the_byte_limit() {
    let catalog = PublicTrackerList::new_with_config_and_fetcher(
        TrackerCatalogConfig {
            enabled: true,
            sources: vec!["custom-source".to_string()],
            update_interval: DEFAULT_TRACKER_UPDATE_INTERVAL,
        },
        Arc::new(OversizedBodyFetcher),
    );

    let error = catalog
        .refresh()
        .await
        .expect_err("custom fetcher output must obey the source body limit");
    assert!(error.contains("exceeds the"), "unexpected error: {error}");
}

#[tokio::test]
async fn refresh_error_reports_only_the_tracker_source_origin() {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    drop(listener);
    let source = format!("http://alice:secret@{address}/private/path?token=private-token#fragment");
    let catalog = PublicTrackerList::new_with_config(TrackerCatalogConfig {
        enabled: true,
        sources: vec![source],
        update_interval: DEFAULT_TRACKER_UPDATE_INTERVAL,
    });

    assert!(catalog.refresh().await.is_err());
    let error = catalog
        .last_refresh_error()
        .await
        .expect("failed refresh should retain a diagnostic");

    assert!(error.contains(&format!("http://{address}/")));
    for secret in [
        "alice",
        "secret",
        "/private/path",
        "private-token",
        "fragment",
    ] {
        assert!(
            !error.contains(secret),
            "diagnostic leaked {secret}: {error}"
        );
    }
}

#[test]
fn tracker_source_diagnostic_origin_removes_userinfo_path_query_and_fragment() {
    assert_eq!(
        tracker_source_origin(
            "https://alice:secret@example.test:8443/private/path?token=private#fragment"
        ),
        "https://example.test:8443/"
    );
    assert_eq!(
        tracker_source_origin("not a URL"),
        "<invalid tracker source URL>"
    );
}

#[test]
fn fetched_tracker_sources_enforce_the_unique_entry_limit() {
    let make_source = |count: usize| {
        (0..count)
            .map(|index| format!("udp://tracker-{index}.example:6969/announce"))
            .collect::<Vec<_>>()
            .join("\n")
    };

    assert_eq!(
        parse_tracker_source_list(&make_source(MAX_TRACKERS_PER_SOURCE))
            .unwrap()
            .len(),
        MAX_TRACKERS_PER_SOURCE
    );
    let error = parse_tracker_source_list(&make_source(MAX_TRACKERS_PER_SOURCE + 1))
        .expect_err("a source above the unique tracker limit must be rejected");
    assert!(
        error.contains("more than 4096"),
        "unexpected error: {error}"
    );
}

#[test]
fn tracker_failure_kind_names_are_stable() {
    assert_eq!(TrackerFailureKind::Network.as_str(), "network");
    assert_eq!(TrackerFailureKind::Timeout.as_str(), "timeout");
    assert_eq!(
        TrackerFailureKind::RemoteTemporary.as_str(),
        "remoteTemporary"
    );
    assert_eq!(
        TrackerFailureKind::TrackerRejected.as_str(),
        "trackerRejected"
    );
    assert_eq!(
        TrackerFailureKind::MalformedResponse.as_str(),
        "malformedResponse"
    );
}

#[test]
fn test_parse_embedded_list() {
    let entries = PublicTrackerList::parse(EMBEDDED_TRACKER_LIST);
    assert!(
        entries.len() >= 50,
        "embedded list should have at least 50 trackers, got {}",
        entries.len()
    );
}

#[test]
fn test_parse_empty_input() {
    let entries = PublicTrackerList::parse("");
    assert!(entries.is_empty(), "empty input should produce empty list");
}

#[test]
fn test_parse_whitespace_only() {
    let entries = PublicTrackerList::parse("\n\n   \n\t\n");
    assert!(entries.is_empty());
}

#[test]
fn test_parse_mixed_protocols() {
    let text = "http://a.com:80/announce\nhttps://b.com:443/announce\nudp://c.com:6969/announce\nwss://d.com:443/announce";
    let entries = PublicTrackerList::parse(text);
    assert_eq!(entries.len(), 4);
    assert_eq!(entries[0].protocol, TrackerProtocol::Http);
    assert_eq!(entries[1].protocol, TrackerProtocol::Https);
    assert_eq!(entries[2].protocol, TrackerProtocol::Udp);
    assert_eq!(entries[3].protocol, TrackerProtocol::Wss);
}

#[test]
fn test_parse_invalid_lines_skipped() {
    let text = "http://valid.com:80/announce\nnot a url\n\nhttp://another.com/announce";
    let entries = PublicTrackerList::parse(text);
    assert_eq!(entries.len(), 2);
}

#[test]
fn test_get_http_trackers_filters_correctly() {
    let ptl = PublicTrackerList::new();
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let http = ptl.get_http_trackers().await;
        for url in &http {
            assert!(
                url.starts_with("http://") || url.starts_with("https://"),
                "{} should be http or https",
                url
            );
            assert!(!url.starts_with("udp://"), "{} should not be udp", url);
        }
        assert!(!http.is_empty(), "should have at least some HTTP trackers");
    });
}

#[test]
fn test_get_udp_trackers_filters_correctly() {
    let ptl = PublicTrackerList::new();
    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async {
        let udp = ptl.get_udp_trackers().await;
        for url in &udp {
            assert!(url.starts_with("udp://"), "{} should be udp", url);
        }
        assert!(!udp.is_empty(), "should have at least some UDP trackers");
    });
}

#[tokio::test]
async fn test_stats_returns_reasonable_values() {
    let ptl = PublicTrackerList::new();
    let stats = ptl.stats().await;
    assert!(stats.total_entries >= 50);
    assert!(stats.http_count > 0);
    assert!(stats.udp_count > 0);
    assert!(
        stats.is_embedded_fallback,
        "default instance uses embedded list"
    );
    assert!(stats.last_updated.is_some());
}

#[tokio::test]
async fn catalog_subscribers_observe_configuration_and_entry_changes() {
    let ptl = PublicTrackerList::new();
    let mut updates = ptl.subscribe_updates();
    let mut revision = *updates.borrow_and_update();

    ptl.set_config(TrackerCatalogConfig {
        enabled: false,
        sources: Vec::new(),
        update_interval: Duration::from_secs(60),
    })
    .await;
    tokio::time::timeout(Duration::from_secs(1), updates.changed())
        .await
        .expect("configuration changes should wake subscribers")
        .expect("catalog update sender should remain open");
    let next_revision = *updates.borrow_and_update();
    assert_eq!(next_revision, revision.wrapping_add(1));
    revision = next_revision;

    let tracker = PublicTrackerList::parse("http://new.example/announce")
        .into_iter()
        .collect();
    ptl.replace_snapshot(tracker)
        .await
        .expect("test catalog snapshot should be valid");
    tokio::time::timeout(Duration::from_secs(1), updates.changed())
        .await
        .expect("entry changes should wake subscribers")
        .expect("catalog update sender should remain open");
    assert_eq!(*updates.borrow_and_update(), revision.wrapping_add(1));
}

#[tokio::test]
async fn test_default_instance_uses_embedded() {
    let ptl = PublicTrackerList::new();
    let all = ptl.get_all().await;
    let embedded_count = PublicTrackerList::parse(EMBEDDED_TRACKER_LIST).len();
    assert_eq!(
        all.len(),
        embedded_count,
        "default instance should use all embedded entries"
    );
}

#[tokio::test]
async fn disabled_catalog_has_no_available_trackers() {
    let ptl = PublicTrackerList::new();
    ptl.set_config(TrackerCatalogConfig {
        enabled: false,
        sources: Vec::new(),
        update_interval: Duration::from_secs(60),
    })
    .await;

    assert!(ptl.available_snapshot().await.is_empty());
    assert!(ptl.get_http_trackers().await.is_empty());
    assert!(ptl.get_udp_trackers().await.is_empty());
    assert!(
        !ptl.get_all().await.is_empty(),
        "disabling availability must not erase the catalog snapshot"
    );
}

#[tokio::test]
async fn empty_source_list_skips_refresh_and_preserves_current_catalog() {
    let ptl = PublicTrackerList::new();
    let initial_snapshot = ptl.snapshot().await;

    ptl.set_config(TrackerCatalogConfig {
        enabled: true,
        sources: Vec::new(),
        update_interval: Duration::from_secs(60),
    })
    .await;

    assert_eq!(ptl.refresh().await.unwrap(), 0);
    assert_eq!(ptl.snapshot().await.as_ref(), initial_snapshot.as_ref());
    assert_eq!(ptl.last_refresh_error().await, None);
}

#[tokio::test]
async fn reenabled_catalog_exposes_existing_snapshot() {
    let ptl = PublicTrackerList::new();
    ptl.set_config(TrackerCatalogConfig {
        enabled: false,
        sources: Vec::new(),
        update_interval: Duration::from_secs(60),
    })
    .await;
    ptl.set_config(TrackerCatalogConfig {
        enabled: true,
        sources: Vec::new(),
        update_interval: Duration::from_secs(60),
    })
    .await;

    assert!(!ptl.available_snapshot().await.is_empty());
}

#[tokio::test]
async fn tracker_backoff_preserves_catalog_and_success_recovers() {
    let ptl = PublicTrackerList::new();
    let entry = PublicTrackerList::parse("http://unhealthy.example/announce")
        .into_iter()
        .next()
        .expect("test tracker should parse");
    ptl.replace_snapshot(vec![entry.clone()]).await.unwrap();

    ptl.record_failure(&entry.url).await;
    ptl.record_failure(&entry.url).await;
    assert!(ptl.contains(&entry.url).await);
    ptl.record_failure(&entry.url).await;

    assert!(ptl.contains(&entry.url).await);
    assert!(ptl.available_snapshot().await.is_empty());

    ptl.record_success(&entry.url).await;
    assert!(!ptl.available_snapshot().await.is_empty());
}

#[tokio::test]
async fn local_failures_do_not_cool_or_remove_tracker() {
    let ptl = PublicTrackerList::new();
    let entry = PublicTrackerList::parse("http://local-network.example/announce")
        .into_iter()
        .next()
        .expect("test tracker should parse");
    ptl.replace_snapshot(vec![entry.clone()]).await.unwrap();

    ptl.record_failure_kind(&entry.url, TrackerFailureKind::Network)
        .await;
    ptl.record_failure_kind(&entry.url, TrackerFailureKind::Timeout)
        .await;

    assert!(ptl.contains(&entry.url).await);
    assert!(
        ptl.available_snapshot()
            .await
            .iter()
            .any(|candidate| candidate.url == entry.url)
    );
}

#[tokio::test]
async fn remote_temporary_failure_is_retriable_and_preserves_catalog() {
    let ptl = PublicTrackerList::new();
    let entry = PublicTrackerList::parse("http://temporary.example/announce")
        .into_iter()
        .next()
        .expect("test tracker should parse");
    ptl.replace_snapshot(vec![entry.clone()]).await.unwrap();

    ptl.record_failure_kind(&entry.url, TrackerFailureKind::RemoteTemporary)
        .await;

    assert!(ptl.contains(&entry.url).await);
    assert!(ptl.available_snapshot().await.is_empty());
    ptl.record_success(&entry.url).await;
    assert!(!ptl.available_snapshot().await.is_empty());
}

#[tokio::test]
async fn explicit_tracker_failure_does_not_hide_or_remove_tracker() {
    let ptl = PublicTrackerList::new();
    let entry = PublicTrackerList::parse("http://rejected.example/announce")
        .into_iter()
        .next()
        .expect("test tracker should parse");
    ptl.replace_snapshot(vec![entry.clone()]).await.unwrap();

    ptl.record_failure_kind(&entry.url, TrackerFailureKind::TrackerRejected)
        .await;

    assert!(ptl.contains(&entry.url).await);
    assert!(
        ptl.available_snapshot()
            .await
            .iter()
            .any(|candidate| candidate.url == entry.url)
    );
}

#[test]
fn test_parse_non_announce_path_rejected() {
    let text = "http://valid.com:80/scrape\nhttp://valid.com:80/announce";
    let entries = PublicTrackerList::parse(text);
    assert_eq!(entries.len(), 1, "non-announce paths should be rejected");
    assert_eq!(entries[0].url, "http://valid.com:80/announce");
}

#[tokio::test]
async fn test_shutdown_sets_flag() {
    let ptl = PublicTrackerList::new();
    assert!(ptl.running.load(Ordering::Relaxed));
    ptl.shutdown();
    assert!(!ptl.running.load(Ordering::Relaxed));
}

#[tokio::test]
async fn test_start_auto_update_starts_task() {
    use std::time::Duration as StdDuration;
    let ptl = Arc::new(PublicTrackerList::new());
    ptl.start_auto_update(
        "https://example.com/fake.txt".to_string(),
        StdDuration::from_secs(999999),
    );
    sleep(Duration::from_millis(50)).await;
    assert!(ptl.running.load(Ordering::Relaxed));
    ptl.shutdown();
}