pub struct BtDownloadCommand {
pub choking_algo: Option<ChokingAlgorithm>,
pub multi_file_layout: Option<MultiFileLayout>,
pub download_path_lock: Option<DownloadPathLock>,
/* private fields */
}Fields§
§choking_algo: Option<ChokingAlgorithm>§multi_file_layout: Option<MultiFileLayout>§download_path_lock: Option<DownloadPathLock>Download path lock held for the lifetime of this command. Prevents other aria2 instances from writing to the same output directory.
Implementations§
Source§impl BtDownloadCommand
impl BtDownloadCommand
pub fn new( gid: GroupId, torrent_bytes: &[u8], options: &DownloadOptions, output_dir: Option<&str>, ) -> Result<Self>
pub async fn group(&self) -> RwLockReadGuard<'_, RequestGroup>
pub fn on_peer_choke(&mut self, peer_idx: usize)
pub fn on_peer_unchoke(&mut self, peer_idx: usize)
pub fn on_data_received_from_peer(&mut self, peer_idx: usize, bytes: u64)
pub fn check_snubbed_peers(&mut self) -> Vec<usize>
pub fn add_peer_to_tracking( &mut self, peer_id: [u8; 8], addr: SocketAddr, ) -> usize
pub fn select_best_peer_for_request(&self) -> Option<usize>
pub async fn handle_snubbed_peer(&mut self, peer_idx: usize) -> Result<()>
pub fn on_piece_received(&mut self, peer_idx: usize, bytes: u64)
Sourcepub fn mark_peer_snubbed(&mut self, peer_idx: usize)
pub fn mark_peer_snubbed(&mut self, peer_idx: usize)
Explicitly mark a peer as snubbed (algorithm-level snubbing).
This adds the peer to the explicit snubbed set, causing them to receive a score of -1000 on the next choke rotation, ensuring they are always choked.
Sourcepub fn is_explicitly_snubbed(&self, peer_idx: usize) -> bool
pub fn is_explicitly_snubbed(&self, peer_idx: usize) -> bool
Check if a peer is explicitly snubbed at the algorithm level.
pub async fn announce_to_public_tracker( tracker_url: &str, info_hash: &[u8; 20], peer_id: &[u8; 20], total_size: u64, ) -> Result<Vec<(String, u16)>, String>
Sourcepub async fn write_piece_to_multi_files(
layout: &MultiFileLayout,
piece_idx: u32,
piece_data: &[u8],
piece_length: u32,
) -> Result<()>
pub async fn write_piece_to_multi_files( layout: &MultiFileLayout, piece_idx: u32, piece_data: &[u8], piece_length: u32, ) -> Result<()>
Wrapper around crate::engine::bt_piece_downloader::write_piece_to_multi_files.
Sourcepub async fn write_piece_to_multi_files_coalesced(
layout: &MultiFileLayout,
piece_idx: u32,
piece_data: &[u8],
piece_length: u32,
) -> Result<()>
pub async fn write_piece_to_multi_files_coalesced( layout: &MultiFileLayout, piece_idx: u32, piece_data: &[u8], piece_length: u32, ) -> Result<()>
Wrapper around crate::engine::bt_piece_downloader::write_piece_to_multi_files_coalesced.
Prefer this over write_piece_to_multi_files for production use — it
merges adjacent writes within a 4 KiB gap, reducing syscall count.
pub fn is_multi_file(&self) -> bool
pub fn get_multi_file_layout(&self) -> Option<&MultiFileLayout>
Sourcepub fn set_progress_manager(&mut self, manager: BtProgressManager)
pub fn set_progress_manager(&mut self, manager: BtProgressManager)
设置 BT 进度管理器
Enable BT download progress persistence for resume support.
When enabled, the engine periodically saves piece completion bitfield,
peer list, and download statistics to a .aria2 file in INI format.
On restart, the progress is loaded to skip already-completed pieces.
§Arguments
manager- An initializedBtProgressManagerinstance
§Example
use aria2_core::engine::bt_progress_info_file::BtProgressManager;
use std::path::PathBuf;
let save_dir = PathBuf::from("/tmp/aria2");
let progress_mgr = BtProgressManager::new(&save_dir).expect("failed to create progress manager");
// Pass progress_mgr to BtDownloadCommand::set_progress_manager()
let _mgr = progress_mgr;Sourcepub fn set_progress_save_interval(&mut self, interval_secs: u64)
pub fn set_progress_save_interval(&mut self, interval_secs: u64)
Set the interval (in seconds) between progress save operations.
§Arguments
interval_secs- Save interval in seconds (default: 60)
Sourcepub fn set_lpd_manager(&mut self, manager: Arc<LpdManager>)
pub fn set_lpd_manager(&mut self, manager: Arc<LpdManager>)
Enable Local Peer Discovery (LPD, BEP 14) for LAN peer finding.
When enabled, the engine announces its active downloads via UDP multicast
to 239.192.152.143:6771 and listens for peers on the same network.
§Arguments
manager- An initializedLpdManager, wrapped inArc
Sourcepub fn set_hook_manager(&mut self, manager: Arc<HookManager>)
pub fn set_hook_manager(&mut self, manager: Arc<HookManager>)
Register a post-download hook chain for completion/error callbacks.
Hooks execute sequentially after download completes or fails. Built-in hook types: Move, Rename, Touch, Exec (shell command). A single hook failure does not block subsequent hooks.
§Arguments
manager- A configuredHookManagerwith registered hooks, wrapped inArc
§Example
use std::collections::HashMap;
use std::sync::Arc;
use aria2_core::engine::bt_post_download_handler::{HookManager, HookConfig, MoveHook, ExecHook};
let config = HookConfig::default();
let mut hooks = HookManager::new(config);
hooks.add_hook(Box::new(MoveHook::new("/completed".into(), true)));
hooks.add_hook(Box::new(ExecHook::new("notify.sh".into(), HashMap::new())));
// Pass Arc::new(hooks) to BtDownloadCommand::set_hook_manager()
let _hooks = Arc::new(hooks);Sourcepub fn get_progress_manager(&self) -> Option<&BtProgressManager>
pub fn get_progress_manager(&self) -> Option<&BtProgressManager>
获取进度管理器引用(用于测试和外部访问)
Sourcepub fn get_lpd_manager(&self) -> Option<&Arc<LpdManager>>
pub fn get_lpd_manager(&self) -> Option<&Arc<LpdManager>>
获取 LPD 管理器引用(用于测试和外部访问)
Sourcepub fn get_hook_manager(&self) -> Option<&Arc<HookManager>>
pub fn get_hook_manager(&self) -> Option<&Arc<HookManager>>
获取钩子管理器引用(用于测试和外部访问)
Sourcepub fn add_pex_peer(&mut self, peer_addr: PeerAddr)
pub fn add_pex_peer(&mut self, peer_addr: PeerAddr)
Add a peer address to the known peers list for PEX exchange
Sourcepub fn set_pex_known_peers(&mut self, peers: Vec<PeerAddr>)
pub fn set_pex_known_peers(&mut self, peers: Vec<PeerAddr>)
Set the list of known peers for PEX exchange
Sourcepub fn get_pex_known_peers(&self) -> &[PeerAddr]
pub fn get_pex_known_peers(&self) -> &[PeerAddr]
Get reference to PEX known peers list
Sourcepub fn set_pex_send_interval(&mut self, interval_secs: u64)
pub fn set_pex_send_interval(&mut self, interval_secs: u64)
Set custom PEX send interval (default 60 seconds)
Sourcepub fn should_send_pex(&self) -> bool
pub fn should_send_pex(&self) -> bool
Check if it’s time to send a PEX message based on rate limiting
Sourcepub fn update_pex_last_send(&mut self)
pub fn update_pex_last_send(&mut self)
Update the last PEX send timestamp
Sourcepub fn endgame_state_mut(&mut self) -> &mut EndgameState
pub fn endgame_state_mut(&mut self) -> &mut EndgameState
Get a mutable reference to the EndgameState for tracking duplicate requests
Sourcepub fn endgame_state(&self) -> &EndgameState
pub fn endgame_state(&self) -> &EndgameState
Get an immutable reference to the EndgameState
Sourcepub fn record_bad_piece_for_peer(
&mut self,
peer_idx: usize,
piece_index: u32,
) -> Result<bool, ()>
pub fn record_bad_piece_for_peer( &mut self, peer_idx: usize, piece_index: u32, ) -> Result<bool, ()>
Record that a specific peer sent invalid piece data (hash verification failed).
This method:
- Increments the peer’s
bad_data_countin the choking algorithm’s PeerStats - If the count reaches
crate::engine::peer_stats::BAD_DATA_THRESHOLD, automatically bans the peer with a reason message - Logs the event at WARN level
§Arguments
peer_idx- The index of the peer in the choking algorithm’s peer listpiece_index- The index of the piece that failed verification
§Returns
Ok(true)if the peer was banned as a result of this callOk(false)if the peer was not banned (count below threshold)Err(())if the peer index is invalid or choking algorithm is not configured
Sourcepub fn record_valid_piece_for_peer(&mut self, peer_idx: usize)
pub fn record_valid_piece_for_peer(&mut self, peer_idx: usize)
Record that a valid, verified piece was received from a peer.
This triggers gradual recovery by decrementing the peer’s bad_data_count.
Call this after successful hash verification to allow peers to recover reputation.
§Arguments
peer_idx- The index of the peer in the choking algorithm’s peer list
Sourcepub fn is_peer_banned(&self, peer_idx: usize) -> bool
pub fn is_peer_banned(&self, peer_idx: usize) -> bool
Sourcepub fn get_peer_stats(&self, peer_idx: usize) -> Option<&PeerStats>
pub fn get_peer_stats(&self, peer_idx: usize) -> Option<&PeerStats>
Get a reference to a peer’s stats for RPC/display purposes.
Returns None if the peer doesn’t exist or no choking algorithm is configured.
Sourcepub fn init_web_seed_manager(&mut self, piece_length: u32, total_length: u64)
pub fn init_web_seed_manager(&mut self, piece_length: u32, total_length: u64)
Initialize the web seed manager if web seeds are configured.
This should be called after the torrent metadata is parsed and before the download loop starts.
§Arguments
piece_length- Length of each piece in the torrenttotal_length- Total file length
Sourcepub fn get_web_seed_manager(&self) -> Option<&WebSeedManager>
pub fn get_web_seed_manager(&self) -> Option<&WebSeedManager>
Get a reference to the web seed manager.
Sourcepub fn get_web_seed_manager_mut(&mut self) -> Option<&mut WebSeedManager>
pub fn get_web_seed_manager_mut(&mut self) -> Option<&mut WebSeedManager>
Get a mutable reference to the web seed manager.
Sourcepub fn has_web_seeds(&self) -> bool
pub fn has_web_seeds(&self) -> bool
Check if web seeds are available.
Sourcepub fn web_seed_stats(&self) -> Option<&WebSeedStats>
pub fn web_seed_stats(&self) -> Option<&WebSeedStats>
Get web seed download statistics.
Sourcepub fn check_and_start_seeding(
&mut self,
piece_picker: &PiecePicker,
meta: &TorrentMeta,
connections: Vec<PeerConnection>,
piece_provider: Arc<dyn PieceDataProvider>,
) -> Result<bool>
pub fn check_and_start_seeding( &mut self, piece_picker: &PiecePicker, meta: &TorrentMeta, connections: Vec<PeerConnection>, piece_provider: Arc<dyn PieceDataProvider>, ) -> Result<bool>
Check if download is complete and start seeding if enabled.
This method should be called after the download loop completes. It initializes the seed manager if:
- All pieces are complete
- Seeding is enabled (seed_ratio > 0 or seed_time > 0)
§Arguments
piece_picker- Reference to the piece picker to check completionmeta- Torrent metadataconnections- Active peer connections to use for seedingpiece_provider- Provider for piece data (from downloaded files)
§Returns
Ok(true)if seeding was startedOk(false)if seeding was not started (not complete or disabled)
Sourcepub fn get_seed_manager(&self) -> Option<&BtSeedManager>
pub fn get_seed_manager(&self) -> Option<&BtSeedManager>
Get a reference to the seed manager.
Sourcepub fn get_seed_manager_mut(&mut self) -> Option<&mut BtSeedManager>
pub fn get_seed_manager_mut(&mut self) -> Option<&mut BtSeedManager>
Get a mutable reference to the seed manager.
Sourcepub fn is_seeding(&self) -> bool
pub fn is_seeding(&self) -> bool
Check if seeding is active.
Sourcepub fn get_seed_stats(&self) -> Option<SeedStats>
pub fn get_seed_stats(&self) -> Option<SeedStats>
Get seeding statistics.
Returns None if not seeding.
Source§impl BtDownloadCommand
impl BtDownloadCommand
Sourcepub fn check_pex_support(
local_extension_ids: &[Option<u8>],
remote_extension_ids: &[Option<u8>],
) -> bool
pub fn check_pex_support( local_extension_ids: &[Option<u8>], remote_extension_ids: &[Option<u8>], ) -> bool
Check if both local and remote peer support ut_pex extension
Sourcepub fn maybe_send_pex(&mut self, remote_peer_addr: &PeerAddr) -> Option<Vec<u8>>
pub fn maybe_send_pex(&mut self, remote_peer_addr: &PeerAddr) -> Option<Vec<u8>>
Build and optionally send a PEX message to connected peers Returns the encoded PEX message (or None if not ready to send)
Sourcepub fn handle_incoming_pex(
&mut self,
pex_data: &[u8],
local_addr: &PeerAddr,
) -> Result<(Vec<PeerAddr>, Vec<PeerAddr>)>
pub fn handle_incoming_pex( &mut self, pex_data: &[u8], local_addr: &PeerAddr, ) -> Result<(Vec<PeerAddr>, Vec<PeerAddr>)>
Process an incoming PEX message and extract discovered/dropped peers
Sourcepub async fn connect_to_pex_discovered_peers(
&mut self,
new_peers: &[PeerAddr],
_info_hash_raw: &[u8; 20],
_num_pieces: u32,
active_connections: &[BtPeerConn],
) -> usize
pub async fn connect_to_pex_discovered_peers( &mut self, new_peers: &[PeerAddr], _info_hash_raw: &[u8; 20], _num_pieces: u32, active_connections: &[BtPeerConn], ) -> usize
Connect to peers discovered via PEX
This method attempts to establish connections with peers that were discovered through PEX (Peer Exchange, BEP 11). It’s called when new peers are added to the PEX known peers list.
§Arguments
new_peers- List of peer addresses discovered via PEXinfo_hash_raw- Torrent info hash for handshakenum_pieces- Total number of pieces for bitfield sizeactive_connections- Current active connections (to avoid duplicates)
§Returns
- Number of successfully connected new peers
Source§impl BtDownloadCommand
impl BtDownloadCommand
pub async fn run_seeding_phase( &mut self, connections: Vec<BtPeerConn>, piece_length: u32, num_pieces: u32, ) -> Result<()>
Trait Implementations§
Source§impl Command for BtDownloadCommand
impl Command for BtDownloadCommand
fn execute<'life0, 'async_trait>(
&'life0 mut self,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
fn status(&self) -> CommandStatus
fn timeout(&self) -> Option<Duration>
Source§fn started_at(&self) -> Option<Instant>
fn started_at(&self) -> Option<Instant>
set_started_at]. Read moreSource§fn set_started_at(&mut self, _instant: Instant)
fn set_started_at(&mut self, _instant: Instant)
started_at].