pub mod interactive;
pub mod piece_provider;
pub mod types;
pub use interactive::BtPeerInteractive;
pub use piece_provider::PieceProvider;
pub use types::{
BtPeerCryptoPolicy, CheckHaveResult, ChokingDecision, DEFAULT_ALLOWED_FAST_SET_SIZE,
DEFAULT_KEEP_ALIVE_INTERVAL_SECS, DEFAULT_MAX_OUTSTANDING_REQUEST, DispatchUpdate,
FLOODING_CHECK_INTERVAL_SECS, INACTIVITY_TIMEOUT_SECS, InteractionResult, InterestDecision,
MAX_UNCHOKE_WAIT_ATTEMPTS, MUTUAL_UNINTERESTED_TIMEOUT_SECS, PEER_CONNECTION_DELAY_MS,
PEER_MESSAGE_TIMEOUT_SECS, PER_SEC_INTERVAL_SECS, PEX_INTERVAL_SECS, PeerConnectionResult,
PeerConnectionState, PeerIdCheckResult, PostHandshakeActions, UB_MAX_OUTSTANDING_REQUEST,
};
use std::time::Duration;
use aria2_protocol::bittorrent::message::types::BtMessage;
use crate::engine::bt_peer_connection::BtPeerConn;
use crate::error::{Aria2Error, RecoverableError, Result};
use tracing::{debug, error, info, warn};
pub struct BtPeerInteraction;
impl BtPeerInteraction {
pub async fn connect_to_peers(
peer_addrs: &[aria2_protocol::bittorrent::peer::connection::PeerAddr],
info_hash_raw: &[u8; 20],
num_pieces: u32,
piece_length: u32,
total_length: u64,
crypto_policy: BtPeerCryptoPolicy,
) -> Result<PeerConnectionResult> {
info!("[BT] Connecting to {} peers...", peer_addrs.len());
let mut active_connections: Vec<BtPeerConn> = Vec::new();
let mut failed_count = 0usize;
for addr in peer_addrs {
debug!("[BT] Connecting to peer {}:{}", addr.ip, addr.port);
match Self::connect_peer_ready(
addr,
info_hash_raw,
crypto_policy,
num_pieces,
piece_length,
total_length,
)
.await
{
Ok(conn) => active_connections.push(conn),
Err(e) => {
error!("[BT] Failed to connect peer {}: {}", addr.ip, e);
failed_count += 1;
}
}
}
info!("[BT] Active connections: {}", active_connections.len());
if active_connections.is_empty() {
return Err(Aria2Error::Recoverable(
RecoverableError::TemporaryNetworkFailure {
message: "All peer connections failed".into(),
},
));
}
Ok(PeerConnectionResult {
connections: active_connections,
failed_count,
})
}
pub async fn connect_peer_ready(
addr: &aria2_protocol::bittorrent::peer::connection::PeerAddr,
info_hash_raw: &[u8; 20],
crypto_policy: BtPeerCryptoPolicy,
num_pieces: u32,
piece_length: u32,
total_length: u64,
) -> Result<BtPeerConn> {
let mut conn = Self::connect_single_peer(addr, info_hash_raw, crypto_policy).await?;
conn.sync_peer_identity();
conn.allocate_session_resource(piece_length, total_length);
info!(
"[BT] Connected to peer {}:{} (encrypted={}, piece_length={}, total_length={})",
addr.ip,
addr.port,
conn.is_encrypted(),
piece_length,
total_length
);
Self::initialize_connection(&mut conn, num_pieces).await?;
if let Err(error) = Self::wait_for_unchoke(&mut conn, addr).await {
warn!("[BT] No unchoke from peer {}: {}", addr.ip, error);
}
Ok(conn)
}
async fn connect_single_peer(
addr: &aria2_protocol::bittorrent::peer::connection::PeerAddr,
info_hash_raw: &[u8; 20],
crypto_policy: BtPeerCryptoPolicy,
) -> Result<BtPeerConn> {
if crypto_policy.require_mse {
BtPeerConn::connect_mse(
addr,
info_hash_raw,
crypto_policy.force_encryption,
crypto_policy.prefer_encryption,
)
.await
} else {
match BtPeerConn::connect_mse(
addr,
info_hash_raw,
crypto_policy.force_encryption,
crypto_policy.prefer_encryption,
)
.await
{
Ok(conn) => Ok(conn),
Err(_) => {
debug!("[BT] MSE failed, trying plain connection");
BtPeerConn::connect_plain(addr, info_hash_raw).await
}
}
}
}
async fn initialize_connection(conn: &mut BtPeerConn, num_pieces: u32) -> Result<()> {
conn.send_unchoke().await?;
conn.send_interested().await?;
let bf_len = (num_pieces as usize).div_ceil(8);
let empty_bf = vec![0u8; bf_len];
conn.send_bitfield(empty_bf).await?;
tokio::time::sleep(Duration::from_millis(PEER_CONNECTION_DELAY_MS)).await;
Ok(())
}
async fn wait_for_unchoke(
conn: &mut BtPeerConn,
addr: &aria2_protocol::bittorrent::peer::connection::PeerAddr,
) -> Result<()> {
debug!("[BT] Waiting for unchoke from {}:{}", addr.ip, addr.port);
for _ in 0..MAX_UNCHOKE_WAIT_ATTEMPTS {
match tokio::time::timeout(
Duration::from_secs(PEER_MESSAGE_TIMEOUT_SECS),
conn.read_message(),
)
.await
{
Ok(Ok(Some(msg))) => {
if matches!(msg, BtMessage::Unchoke) {
info!("[BT] Got unchoke from {}:{}", addr.ip, addr.port);
return Ok(());
}
debug!("[BT] Got message while waiting for unchoke: {:?}", msg);
}
Ok(Ok(None)) => {
warn!("[BT] EOF from peer while waiting for unchoke");
return Err(Aria2Error::Recoverable(
RecoverableError::TemporaryNetworkFailure {
message: "Peer closed connection".into(),
},
));
}
Ok(Err(e)) => {
error!("[BT] Error reading from peer: {}", e);
return Err(Aria2Error::Recoverable(
RecoverableError::TemporaryNetworkFailure {
message: format!("Read error: {}", e),
},
));
}
Err(_) => {
debug!("[BT] Timeout reading from peer, retrying...");
}
}
}
warn!(
"[BT] Did not receive unchoke from {}:{} after {} attempts",
addr.ip, addr.port, MAX_UNCHOKE_WAIT_ATTEMPTS
);
Ok(()) }
pub async fn broadcast_have(connections: &mut [BtPeerConn], piece_index: u32) {
for conn in connections.iter_mut() {
if let Err(e) = conn.send_have(piece_index).await {
warn!("[BT] Failed to send HAVE to peer: {}", e);
}
}
}
pub fn peer_tracker_key(conn: &BtPeerConn) -> String {
conn.remote_peer_id()
.map(|id| String::from_utf8_lossy(&id).into_owned())
.unwrap_or_else(|| format!("{}:{}", conn.ip_addr, conn.port))
}
pub fn initialize_peer_tracking(
connections: &[BtPeerConn],
_num_pieces: u32,
peer_tracker: &mut aria2_protocol::bittorrent::piece::peer_tracker::PeerBitfieldTracker,
) {
for conn in connections {
let peer_key = Self::peer_tracker_key(conn);
let bitfield = conn
.session_resource
.as_ref()
.map_or(&[][..], |resource| resource.bitfield());
peer_tracker.update_peer_bitfield(&peer_key, bitfield);
}
debug!(
"[BT] Initialized peer tracking for {} peers",
connections.len()
);
}
pub fn cleanup_connections(connections: &mut [BtPeerConn]) {
for conn in connections.iter_mut() {
let _ = conn;
}
debug!("[BT] Cleaned up {} connections", connections.len());
}
}
#[cfg(test)]
mod tests;