aria2-core 0.2.8

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
mod bep6;
mod dht_periodic_lookup;
mod finalization;
mod peer_management;
mod pex;
mod piece_download;
mod web_seed;

pub use dht_periodic_lookup::{DhtPeriodicLookup, check_periodic_dht_lookup};

use async_trait::async_trait;
use std::collections::HashSet;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, info, warn};

use super::types::PeerKey;
use crate::config::parse_integer_segments;
use crate::engine::bt_download_command::BtDownloadCommand;
use crate::engine::command::{Command, CommandStatus};
use crate::error::{Aria2Error, FatalError, Result};
use crate::filesystem::control_file::ControlFile;
use crate::request::request_group::GroupId;
use crate::util::rwlock_ext::RwLockRecover;

impl BtDownloadCommand {
    fn drain_incoming_peers(
        &mut self,
        active_connections: &mut Vec<crate::engine::bt_peer_connection::BtPeerConn>,
        piece_length: u32,
        total_size: u64,
    ) {
        let Some(receiver) = self.incoming_peers.as_mut() else {
            return;
        };
        while let Ok(incoming) = receiver.try_recv() {
            let endpoint = incoming.endpoint;
            let mut conn = crate::engine::bt_peer_connection::BtPeerConn::from_incoming_plain(
                incoming.connection,
                endpoint,
            );
            let remote_peer_id = conn.remote_peer_id();
            if remote_peer_id == Some(self.local_peer_id)
                || remote_peer_id.is_some_and(|peer_id| {
                    active_connections
                        .iter()
                        .any(|active| active.peer_id == Some(peer_id))
                })
            {
                self.peer_storage
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .return_peer_by_endpoint(&endpoint.ip().to_string(), endpoint.port());
                info!(%endpoint, "Rejected incoming self or duplicate BitTorrent peer");
                continue;
            }
            conn.allocate_session_resource(piece_length, total_size);
            active_connections.push(conn);
            self.bt_runtime.set_connections(active_connections.len());
            info!("[BT] Admitted incoming peer {}", endpoint);
        }
    }
}

#[async_trait]
impl Command for BtDownloadCommand {
    async fn shutdown(&mut self) {
        BtDownloadCommand::shutdown(self).await;
    }

    async fn execute(&mut self) -> Result<()> {
        if !self.started {
            self.group.recover_mut().start()?;
            self.started = true;
            self.started_at = Some(Instant::now());
        }

        // Register this BT download into the engine's BtRegistry so that
        // info-hash reverse lookup, peer blocklist, and cross-download BT
        // coordination work end-to-end. In C++ aria2, this is done by
        // `BtSetup::setup()` which calls `BtRegistry::put(gid, btObject)`.
        if let Some(ref registry) = self.bt_registry {
            let gid = self.group.recover().gid().value();
            let download_context = self.group.recover().get_download_context();

            // Build BtAnnounce from the torrent's announce list / announce URL.
            // In C++ aria2, BtSetup creates BtAnnounce from TorrentAttribute's
            // announce list and passes it to BtRegistry.
            let (announce_list, announce_url) = {
                use crate::download::download_context::{ContextAttributeType, TorrentAttribute};
                if let Some(ref ctx) = download_context {
                    if let Some(attr) = ctx.get_attribute(ContextAttributeType::BitTorrent) {
                        if let Some(ta) = attr.downcast_ref::<TorrentAttribute>() {
                            let list = &ta.announce_list;
                            let url = ta
                                .announce_list
                                .first()
                                .and_then(|tier| tier.first())
                                .cloned();
                            (list.clone(), url)
                        } else {
                            (Vec::new(), None)
                        }
                    } else {
                        (Vec::new(), None)
                    }
                } else {
                    (Vec::new(), None)
                }
            };
            let bt_announce = Arc::new(crate::engine::bt_tracker_comm::BtAnnounce::new(
                &announce_list,
                &announce_url,
            ));
            let bt_object = crate::engine::bt_registry::BtObject::builder()
                .bt_announce(bt_announce)
                .download_context(download_context.unwrap_or_else(|| {
                    Arc::new(crate::download::DownloadContext::new(0, 0, String::new()))
                }))
                .peer_rejection(self.peer_rejection.clone())
                .build();
            if let Ok(mut reg) = registry.write() {
                reg.put(gid, bt_object);
                info!(
                    gid,
                    "Registered BT download into BtRegistry with BtAnnounce"
                );
            }
        }

        let (meta, piece_length, total_size, num_pieces) = self.prepare_environment().await?;
        self.group
            .recover()
            .set_control_file_path(ControlFile::control_path_for(&self.output_path));

        // --check-integrity: verify existing data against the torrent's piece
        // hashes before allocating/downloading (mirrors C++
        // CheckIntegrityMan + CheckIntegrityCommand).
        let mut verified_piece_indices = Vec::new();
        if self.check_integrity {
            use crate::checksum::check_integrity::man as ci_man;
            use crate::checksum::message_digest::HashType;
            use crate::util::rwlock_ext::RwLockRecover;
            let gid = self.group.recover().gid().value();
            let piece_hashes_hex: Vec<String> = meta.info.pieces.iter().map(hex::encode).collect();
            let task = if let Some(ref layout) = self.multi_file_layout {
                let files: Vec<_> = layout
                    .file_list()
                    .iter()
                    .filter_map(|entry| {
                        layout
                            .file_absolute_path(entry.index)
                            .map(|path| (path.to_path_buf(), entry.length))
                    })
                    .collect();
                ci_man::cut_multi_file_trailing_garbage(&files).await?;
                ci_man::multi_file_task(
                    files,
                    piece_length as u64,
                    total_size,
                    piece_hashes_hex,
                    HashType::Sha1,
                )?
            } else {
                ci_man::cut_trailing_garbage(&self.output_path, total_size).await?;
                ci_man::file_task(
                    &self.output_path,
                    piece_length as u64,
                    total_size,
                    piece_hashes_hex,
                    HashType::Sha1,
                )?
            };
            if let Some(task) = task {
                info!(
                    gid,
                    "Checking integrity of existing data against piece hashes"
                );
                let outcome = ci_man::enqueue_with_outcome(&ci_man::shared(), gid, task).await?;
                verified_piece_indices = outcome.verified_piece_indices;
                if !outcome.failed_piece_indices.is_empty() {
                    warn!(
                        gid,
                        failed_pieces = ?outcome.failed_piece_indices,
                        "Integrity check found pieces to re-download"
                    );
                }
                // Only verified pieces enter the picker as complete. Failed
                // pieces are intentionally left missing, which makes the
                // runtime piece manager request them again rather than relying
                // on stale control-file state.
                info!(
                    gid,
                    verified_pieces = verified_piece_indices.len(),
                    "Integrity check completed, proceeding with download"
                );
            }
        }

        if self.hash_check_only {
            info!("hash-check-only enabled; stopping after integrity validation");
            if self.check_integrity && verified_piece_indices.len() == num_pieces as usize {
                self.completed_bytes = total_size;
                self.progress.set_completed_length(total_size);
                self.group.recover_mut().complete()?;
                info!("hash-check-only completed successfully");
                return Ok(());
            }
            return Err(Aria2Error::Fatal(FatalError::Config(
                "hash-check-only: existing data failed torrent piece hash validation".into(),
            )));
        }

        // File pre-allocation (mirrors C++ BtFileAllocationEntry queued into
        // FileAllocationMan after integrity checking). Single-file torrents
        // allocate `output_path`; multi-file torrents allocate every file in
        // layout order. Already-completed files are skipped by the worker.
        // The worker runs chunked, cooperative allocation sequentially across
        // downloads, so a huge zero-fill never blocks this task or the engine.
        {
            use crate::filesystem::file_allocation::AllocationStrategy;
            use crate::filesystem::file_allocation_man;
            let strategy = AllocationStrategy::from_str(&self.file_allocation);
            if strategy != AllocationStrategy::None {
                let gid = self.group.recover().gid().value();
                let man = file_allocation_man::shared();
                if let Some(ref layout) = self.multi_file_layout {
                    let files: Vec<(std::path::PathBuf, u64)> = layout
                        .file_list()
                        .iter()
                        .filter_map(|f| {
                            layout
                                .file_absolute_path(f.index)
                                .map(|p| (p.to_path_buf(), f.length))
                        })
                        .collect();
                    file_allocation_man::enqueue_multi(
                        &man,
                        files,
                        strategy,
                        self.secure_falloc,
                        gid,
                    )
                    .await?;
                } else {
                    file_allocation_man::enqueue_path(
                        &man,
                        &self.output_path,
                        total_size,
                        strategy,
                        self.secure_falloc,
                        gid,
                    )
                    .await?;
                }
            }
        }

        // P1 integration: try to resume from saved .aria2 progress file
        if let Some(ref mgr) = self.progress_manager {
            match mgr.load_progress(&meta.info_hash.bytes) {
                Ok(saved) => {
                    info!(
                        pieces_done = saved.num_pieces,
                        ratio = saved.completion_ratio(),
                        "Resuming from saved progress"
                    );
                }
                Err(e) => {
                    debug!(
                        error = %e,
                        "No saved progress found, starting fresh download"
                    );
                }
            }
        }

        // BtSetup/PeerListenCommand counterpart: create the session-scoped
        // listener before discovery so a torrent with no initial peers can
        // still accept an incoming connection.
        if self.incoming_peers.is_none() {
            let (listen_ports, max_peers, caretaker_id, disable_ipv6) = {
                let group = self.group.recover();
                let ports = group
                    .options()
                    .listen_port
                    .as_deref()
                    .map(parse_listen_ports)
                    .transpose()
                    .map_err(|error| Aria2Error::Fatal(FatalError::Config(error)))?
                    .unwrap_or_else(|| vec![0]);
                (
                    ports,
                    group.options().bt_max_peers,
                    group.gid().value(),
                    group.options().disable_ipv6,
                )
            };
            let bind_listener = |bind_ip: std::net::IpAddr| {
                crate::engine::bt_peer_listener::BtPeerListener::bind_ports(
                    bind_ip,
                    listen_ports.clone(),
                    meta.info_hash.bytes,
                    self.local_peer_id,
                    caretaker_id,
                    max_peers,
                    std::sync::Arc::clone(&self.peer_storage),
                )
            };
            let listener = if disable_ipv6 {
                bind_listener(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)).await
            } else {
                match bind_listener(std::net::IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED)).await {
                    Ok(listener) => Ok(listener),
                    Err(ipv6_error) => {
                        warn!(
                            error = %ipv6_error,
                            "IPv6 BitTorrent listener unavailable; falling back to IPv4"
                        );
                        bind_listener(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)).await
                    }
                }
            }
            .map_err(|error| {
                Aria2Error::Recoverable(crate::error::RecoverableError::TemporaryNetworkFailure {
                    message: format!("failed to bind BitTorrent peer listener: {error}"),
                })
            })?;
            let actual_addr = listener.local_addr().map_err(|error| {
                Aria2Error::Recoverable(crate::error::RecoverableError::TemporaryNetworkFailure {
                    message: format!("failed to query BitTorrent listener address: {error}"),
                })
            })?;
            self.listen_port = actual_addr.port();
            if let Some(registry) = &self.bt_registry
                && let Ok(mut registry) = registry.write()
            {
                registry.set_tcp_port(self.listen_port);
            }
            let (incoming_peers, listener_task) = listener.spawn(max_peers.max(1));
            self.incoming_peers = Some(incoming_peers);
            self.incoming_peer_listener_task = Some(listener_task);
            info!("[BT] Incoming peer listener bound at {}", actual_addr);
        }

        let peer_addrs = self
            .discover_peers(&meta, total_size, &meta.info_hash.bytes)
            .await?;

        let mut active_connections = if peer_addrs.is_empty() {
            Vec::new()
        } else {
            self.connect_to_peers(
                &peer_addrs,
                &meta.info_hash.bytes,
                num_pieces,
                piece_length,
                total_size,
            )
            .await?
        };

        // Initialize PEX known peers list from discovered peers for BEP 11 exchange.
        // BEP 0027 (Private Torrent): PEX must be disabled for private torrents
        // because it exchanges peer lists with connected peers, which would leak
        // the swarm membership beyond the tracker-controlled peer set.
        if self.is_private {
            info!("[BT] Private torrent: PEX disabled (BEP 0027)");
        } else {
            let pex_peers: Vec<aria2_protocol::bittorrent::peer::connection::PeerAddr> = peer_addrs
                .iter()
                .map(|pa| {
                    aria2_protocol::bittorrent::peer::connection::PeerAddr::new(&pa.ip, pa.port)
                })
                .collect();
            self.set_pex_known_peers(pex_peers);
            info!(
                "[PEX] Initialized with {} known peers from tracker/DHT",
                self.pex_known_peers.len()
            );
        }

        // Initialize web seed manager if web seeds are available (BEP 19)
        let web_seed_manager = if !self.web_seed_urls.is_empty() {
            info!(
                "[BT] Initializing web seed manager with {} URL(s)",
                self.web_seed_urls.len()
            );
            Some(crate::engine::bt_web_seed::WebSeedManager::new(
                self.web_seed_urls.clone(),
                piece_length,
                total_size,
            ))
        } else {
            None
        };

        // Initialize PEX state only for peers whose BEP 10 handshake advertised
        // ut_pex. Private torrents keep this set empty per BEP 0027.
        let mut pex_enabled_peers: HashSet<PeerKey> = HashSet::new();
        let mut last_pex_send = Instant::now();
        const PEX_SEND_INTERVAL_SECS: u64 = 60;

        if !self.is_private {
            // PEX is enabled only after the remote BEP 10 handshake advertises
            // ut_pex. Each peer has an independent extension-ID namespace.
            for conn in active_connections.iter() {
                if conn.peer_extension_id("ut_pex").is_some()
                    && let Some(peer_key) = PeerKey::from_peer(&conn.ip_addr, conn.port)
                {
                    pex_enabled_peers.insert(peer_key);
                }
            }
            info!(
                "[PEX] Initialized PEX tracking for {} negotiated peers",
                pex_enabled_peers.len()
            );
        }

        // BEP 6 (Fast Extension): Send initial AllowedFast messages to
        // peers that support fast extension. The fast-set is computed from
        // the peer's IP address (see compute_fast_set in fast_set.rs).
        // Also, for peers that support fast extension, we can send HaveAll
        // or HaveNone instead of a full Bitfield when appropriate.
        for (idx, conn) in active_connections.iter_mut().enumerate() {
            if conn.is_fast_extension_enabled() {
                let mut sent = HashSet::new();
                match Self::send_allowed_fast_for_torrent(
                    conn,
                    num_pieces,
                    &meta.info_hash.bytes,
                    &mut sent,
                )
                .await
                {
                    Ok(count) if count > 0 => {
                        if let Some(peer_key) = PeerKey::from_peer(&conn.ip_addr, conn.port) {
                            self.allowed_fast_sent_peers.insert(peer_key, sent);
                        }
                        debug!(
                            "[BEP6] Sent {} AllowedFast pieces to peer {} ({})",
                            count, idx, conn.ip_addr
                        );
                    }
                    Ok(_) => {}
                    Err(e) => {
                        warn!("[BEP6] Failed to flush AllowedFast to peer {}: {}", idx, e);
                    }
                }
            }
        }

        // Admit handshaken incoming peers before the first piece cycle. Later
        // cycles drain the receiver below, preserving PeerListenCommand's
        // long-lived listener semantics.
        self.drain_incoming_peers(&mut active_connections, piece_length, total_size);

        // Download pieces from the connected peers, using web seeds and PEX as configured.
        let piece_result = self
            .download_pieces_loop(
                &mut active_connections,
                &meta,
                piece_length,
                total_size,
                num_pieces,
                web_seed_manager.as_ref(),
                &mut pex_enabled_peers,
                &mut last_pex_send,
                PEX_SEND_INTERVAL_SECS,
                &verified_piece_indices,
            )
            .await;
        self.group.recover().clear_bt_peer_snapshots();
        if let Err(error) = piece_result {
            if let Some(ref mut announcer) = self.tracker_announcer {
                announcer
                    .announce_stopped(
                        &meta.info_hash.bytes,
                        &self.local_peer_id,
                        self.completed_bytes,
                        total_size.saturating_sub(self.completed_bytes),
                        self.total_uploaded,
                    )
                    .await;
            }
            return Err(error);
        }

        if let Some(ref mut announcer) = self.tracker_announcer {
            announcer
                .announce_completed(
                    &meta.info_hash.bytes,
                    &self.local_peer_id,
                    self.completed_bytes,
                    self.total_uploaded,
                )
                .await;
        }

        if self.seed_enabled && !active_connections.is_empty() {
            info!(
                "Starting seeding phase with {} peers...",
                active_connections.len()
            );
            self.run_seeding_phase(
                active_connections,
                piece_length,
                num_pieces,
                meta.info_hash.bytes,
            )
            .await?;
        } else {
            info!(
                "Skipping seeding (enabled={}, connections={})",
                self.seed_enabled,
                active_connections.len()
            );
            for conn in &mut active_connections {
                let _ = conn;
            }
        }

        let started_at = self.started_at.unwrap_or_else(Instant::now);
        self.finalize_download(started_at, &meta).await?;

        Ok(())
    }

    fn status(&self) -> CommandStatus {
        if self.completed_bytes > 0 {
            CommandStatus::Running
        } else {
            CommandStatus::Pending
        }
    }

    fn gid(&self) -> GroupId {
        self.group.recover().gid()
    }

    fn request_group(
        &self,
    ) -> Option<std::sync::Arc<std::sync::RwLock<crate::request::request_group::RequestGroup>>>
    {
        Some(std::sync::Arc::clone(&self.group))
    }

    fn timeout(&self) -> Option<Duration> {
        Some(Duration::from_secs(600))
    }
}

fn parse_listen_ports(value: &str) -> std::result::Result<Vec<u16>, String> {
    let ports = parse_integer_segments(value, 1024, u16::MAX as i64)?
        .into_iter()
        .flat_map(|range| range.map(|port| port as u16))
        .collect::<Vec<_>>();
    Ok(ports)
}

impl BtDownloadCommand {
    /// Prepare the download environment: create output directories, parse torrent metadata, and set total length on the request group.
    async fn prepare_environment(
        &mut self,
    ) -> Result<(
        aria2_protocol::bittorrent::torrent::parser::TorrentMeta,
        u32,
        u64,
        u32,
    )> {
        if let Some(parent) = self.output_path.parent()
            && !parent.exists()
        {
            std::fs::create_dir_all(parent).map_err(|e| {
                Aria2Error::Fatal(FatalError::Config(format!("mkdir failed: {}", e)))
            })?;
        }

        if let Some(ref layout) = self.multi_file_layout {
            layout.create_directories().map_err(|e| {
                Aria2Error::Fatal(FatalError::Config(format!(
                    "create_directories failed: {}",
                    e
                )))
            })?;
            info!(
                "[BT] Multi-file mode: {} files under {}",
                layout.num_files(),
                self.output_path.display()
            );
        }

        let meta =
            aria2_protocol::bittorrent::torrent::parser::TorrentMeta::parse(&self.torrent_data)
                .map_err(|e| {
                    Aria2Error::Fatal(FatalError::Config(format!("Torrent parse error: {}", e)))
                })?;

        {
            let g = self.group.recover();
            g.set_total_length(meta.total_size());
        }

        let piece_length = meta.info.piece_length;
        let total_size = meta.total_size();
        let num_pieces = meta.num_pieces() as u32;

        Ok((meta, piece_length, total_size, num_pieces))
    }
}

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

    #[test]
    fn listen_port_parser_expands_original_segment_syntax() {
        assert_eq!(
            parse_listen_ports("6881-6883,6999").unwrap(),
            vec![6881, 6882, 6883, 6999]
        );
    }

    #[test]
    fn listen_port_parser_rejects_values_outside_original_bounds() {
        assert!(parse_listen_ports("1023").is_err());
        assert!(parse_listen_ports("70000").is_err());
        assert!(parse_listen_ports("6881-").is_err());
    }
}