mod choke_api;
mod constructor;
mod integration_api;
mod peer_ban_api;
mod seed_api;
mod web_seed_api;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crate::engine::choking_algorithm::ChokingAlgorithm;
use crate::engine::http_tracker_client::TrackerState;
use crate::engine::lpd_manager::LpdManager;
use crate::engine::multi_file_layout::MultiFileLayout;
use crate::rate_limiter::RateLimiter;
use crate::request::request_group::{AtomicProgress, RequestGroup};
pub use crate::engine::bt_message_handler::{
BLOCK_REQUEST_TIMEOUT_SECS, BLOCK_SIZE, MAX_BLOCK_READ_MESSAGES, MAX_RETRIES,
};
pub use crate::engine::bt_peer_interaction::{
MAX_UNCHOKE_WAIT_ATTEMPTS, PEER_CONNECTION_DELAY_MS, PEER_MESSAGE_TIMEOUT_SECS,
};
pub use crate::engine::bt_piece_selector::ENDGAME_THRESHOLD;
pub(crate) use constructor::{
apply_file_mappings, apply_select_file_filter, build_download_context_from_meta,
};
pub use seed_api::SeedStats;
pub(crate) const MAX_PUBLIC_TRACKERS_TO_TRY: usize = 10;
#[derive(Debug)]
pub(crate) struct BtRuntimeState {
connections: std::sync::atomic::AtomicUsize,
max_peers: std::sync::atomic::AtomicUsize,
}
impl BtRuntimeState {
pub(crate) fn new(max_peers: usize) -> Self {
Self {
connections: std::sync::atomic::AtomicUsize::new(0),
max_peers: std::sync::atomic::AtomicUsize::new(max_peers),
}
}
pub(crate) fn set_connections(&self, connections: usize) {
self.connections
.store(connections, std::sync::atomic::Ordering::Release);
}
pub(crate) fn set_max_peers(&self, max_peers: usize) {
self.max_peers
.store(max_peers, std::sync::atomic::Ordering::Release);
}
pub(crate) fn connections(&self) -> usize {
self.connections.load(std::sync::atomic::Ordering::Acquire)
}
pub(crate) fn max_peers(&self) -> usize {
self.max_peers.load(std::sync::atomic::Ordering::Acquire)
}
pub(crate) fn min_peers(&self) -> usize {
let max_peers = self.max_peers.load(std::sync::atomic::Ordering::Acquire);
if max_peers == 0 {
0
} else {
(max_peers * 4 / 5).max(1)
}
}
pub(crate) fn less_than_min_peers(&self) -> bool {
self.connections() < self.min_peers()
}
pub(crate) fn less_than_max_peers(&self) -> bool {
self.max_peers() == 0 || self.connections() < self.max_peers()
}
}
impl Drop for BtDownloadCommand {
fn drop(&mut self) {
self.bt_peer_route.take();
let mut storage = self
.peer_storage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let peers: Vec<_> = storage.used_peers().iter().cloned().collect();
for peer in peers {
storage.return_peer(&peer);
}
}
}
pub struct BtDownloadCommand {
pub(crate) local_peer_id: [u8; 20],
pub(crate) group: Arc<std::sync::RwLock<RequestGroup>>,
pub(crate) progress: Arc<AtomicProgress>,
pub(crate) output_path: std::path::PathBuf,
pub(crate) started: bool,
pub(crate) started_at: Option<Instant>,
pub(crate) completed_bytes: u64,
pub(crate) torrent_data: Vec<u8>,
pub(crate) seed_enabled: bool,
pub(crate) seed_time: Option<std::time::Duration>,
pub(crate) seed_ratio: Option<f64>,
pub(crate) total_uploaded: u64,
pub(crate) udp_client: Option<crate::engine::udp_tracker_client::SharedUdpClient>,
pub(crate) tracker_announcer: Option<crate::engine::bt_tracker_comm::TrackerAnnouncer>,
pub(crate) listen_port: u16,
pub(crate) bt_runtime: std::sync::Arc<BtRuntimeState>,
pub(crate) peer_coordinator: crate::engine::bt_peer_coordinator::BtPeerCoordinator,
pub(crate) dht_engine:
Option<std::sync::Arc<aria2_protocol::bittorrent::dht::engine::DhtEngine>>,
pub(crate) public_trackers:
Option<std::sync::Arc<aria2_protocol::bittorrent::tracker::public_list::PublicTrackerList>>,
pub(crate) public_tracker_urls: HashSet<String>,
pub(crate) choking_algo: Option<ChokingAlgorithm>,
pub(crate) multi_file_layout: Option<MultiFileLayout>,
pub(crate) file_allocation: String,
pub(crate) secure_falloc: bool,
pub(crate) check_integrity: bool,
pub(crate) hash_check_only: bool,
pub(crate) bt_enable_hook_after_hash_check: bool,
pub(crate) bt_hash_check_seed: bool,
pub(crate) hash_check_completed: bool,
pub(crate) bt_complete_event_emitted: bool,
pub(crate) progress_manager: Option<crate::engine::bt_progress_info_file::BtProgressManager>,
pub(crate) progress_save_interval: Duration,
pub(crate) lpd_manager: Option<Arc<LpdManager>>,
pub(crate) hook_manager: Option<Arc<crate::engine::hook_manager::HookManager>>,
pub(crate) pex_known_peers: Vec<aria2_protocol::bittorrent::peer::connection::PeerAddr>,
pub(crate) pex_last_send_time: Option<Instant>,
pub(crate) pex_send_interval: Duration,
pub(crate) endgame_state: super::bt_download_execute::EndgameState,
#[allow(dead_code)]
pub(crate) allowed_fast_sent_peers:
HashMap<super::bt_download_execute::types::PeerKey, HashSet<u32>>,
pub(crate) suggest_sent_counts: HashMap<super::bt_download_execute::types::PeerKey, usize>,
#[allow(dead_code)]
pub(crate) tracker_state: TrackerState,
pub(crate) web_seed_urls: Vec<String>,
pub(crate) web_seed_manager: Option<crate::engine::bt_web_seed::WebSeedManager>,
pub(crate) dht_periodic_lookup: super::bt_download_execute::execute::DhtPeriodicLookup,
pub download_path_lock: Option<crate::filesystem::file_lock::DownloadPathLock>,
pub(crate) seed_manager: Option<super::bt_seed_manager::BtSeedManager>,
pub(crate) is_private: bool,
pub(crate) bt_registry: Option<Arc<std::sync::RwLock<super::bt_registry::BtRegistry>>>,
pub(crate) global_limiter: Option<RateLimiter>,
pub(crate) peer_rejection: crate::engine::bt_peer_storage::SharedPeerRejection,
pub(crate) peer_storage:
std::sync::Arc<std::sync::Mutex<crate::engine::bt_peer_storage::DefaultPeerStorage>>,
pub(crate) incoming_peers:
Option<tokio::sync::mpsc::Receiver<crate::engine::bt_peer_listener::IncomingPeer>>,
pub(crate) bt_listener: Option<Arc<crate::engine::bt_peer_listener::BtPeerListenerManager>>,
pub(crate) bt_peer_route: Option<crate::engine::bt_peer_listener::BtPeerRouteHandle>,
pub(crate) checkpoint: Option<crate::engine::bt_checkpoint::BtCheckpoint>,
}
impl BtDownloadCommand {
pub fn group(&self) -> std::sync::RwLockReadGuard<'_, RequestGroup> {
use crate::util::rwlock_ext::RwLockRecover;
self.group.recover()
}
pub fn group_handle(&self) -> Arc<std::sync::RwLock<RequestGroup>> {
Arc::clone(&self.group)
}
pub async fn shutdown(&mut self) {
if let Ok(meta) =
aria2_protocol::bittorrent::torrent::parser::TorrentMeta::parse(&self.torrent_data)
&& let Some(ref mut announcer) = self.tracker_announcer
{
let total_size = meta.total_size();
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;
}
self.bt_peer_route.take();
}
pub fn set_global_limiter(&mut self, limiter: RateLimiter) {
self.global_limiter = Some(limiter);
}
pub fn is_multi_file(&self) -> bool {
self.multi_file_layout
.as_ref()
.is_some_and(|l| l.is_multi_file())
}
pub fn get_multi_file_layout(&self) -> Option<&MultiFileLayout> {
self.multi_file_layout.as_ref()
}
pub async fn write_piece_to_multi_files(
layout: &MultiFileLayout,
piece_idx: u32,
piece_data: &[u8],
piece_length: u32,
) -> crate::error::Result<()> {
crate::engine::bt_piece_downloader::write_piece_to_multi_files(
layout,
piece_idx,
piece_data,
piece_length,
)
.await
}
pub async fn write_piece_to_multi_files_coalesced(
layout: &MultiFileLayout,
piece_idx: u32,
piece_data: &bytes::Bytes,
piece_length: u32,
) -> crate::error::Result<()> {
crate::engine::bt_piece_downloader::write_piece_to_multi_files_coalesced(
layout,
piece_idx,
piece_data,
piece_length,
)
.await
}
pub async fn announce_to_public_tracker(
tracker_url: &str,
info_hash: &[u8; 20],
peer_id: &[u8; 20],
total_size: u64,
) -> std::result::Result<Vec<(String, u16)>, String> {
crate::engine::bt_tracker_comm::announce_to_public_tracker(
tracker_url,
info_hash,
peer_id,
total_size,
)
.await
}
}
#[cfg(test)]
mod tests {
use super::{BtDownloadCommand, BtRuntimeState};
#[test]
fn runtime_state_uses_the_same_min_peer_boundary_as_tracker_demand() {
let runtime = BtRuntimeState::new(55);
assert_eq!(runtime.min_peers(), 44);
assert!(runtime.less_than_min_peers());
runtime.set_connections(44);
assert!(!runtime.less_than_min_peers());
runtime.set_max_peers(0);
assert_eq!(runtime.min_peers(), 0);
assert!(!runtime.less_than_min_peers());
assert!(runtime.less_than_max_peers());
}
#[test]
fn runtime_state_accepts_runtime_max_peer_changes() {
let runtime = BtRuntimeState::new(10);
runtime.set_connections(7);
assert!(runtime.less_than_min_peers());
runtime.set_max_peers(8);
assert!(!runtime.less_than_min_peers());
assert_eq!(runtime.max_peers(), 8);
}
#[test]
fn explicit_zero_seed_time_overrides_the_default_seed_ratio() {
let torrent = crate::engine::bt_download_command_tests::build_test_torrent();
let options = crate::request::request_group::DownloadOptions {
seed_time: Some(0.0),
..Default::default()
};
let command = BtDownloadCommand::new(
crate::request::request_group::GroupId::new(10),
&torrent,
&options,
None,
)
.expect("test torrent should construct");
assert!(!command.seed_enabled);
}
#[test]
fn positive_seed_options_enable_seeding() {
let torrent = crate::engine::bt_download_command_tests::build_test_torrent();
let options = crate::request::request_group::DownloadOptions {
seed_time: Some(1.0),
..Default::default()
};
let command = BtDownloadCommand::new(
crate::request::request_group::GroupId::new(11),
&torrent,
&options,
None,
)
.expect("test torrent should construct");
assert!(command.seed_enabled);
assert_eq!(
command.seed_time,
Some(std::time::Duration::from_secs(60)),
"seed-time is expressed in fractional minutes"
);
}
}