aria2-core 0.3.14

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
//! BT peer connection manager and initialization path.
//!
//! This module manages engine-side policy and lifecycle for peer attempts:
//! - Selecting uTP, MSE, or plain TCP and applying fallback rules
//! - Applying outbound-network policy before protocol handshakes
//! - Checking peer identity and preparing the long-lived Swarm actor
//!
//! The protocol crate performs the BitTorrent and MSE handshakes.
//!
//! # Compatibility Reference
//!
//! Protocol behavior is checked against original aria2's:
//! - `src/PeerInteractionCommand.h/.cc` — Peer connection lifecycle command
//! - `src/PeerConnection.cc/h` — Peer connection management
//!   This module does not own post-handshake protocol I/O; the peer actor does.

mod types;

pub use types::{BtPeerConnectionOptions, BtPeerCryptoPolicy, PeerConnectionResult};

// ======================================================================
// BtPeerInteraction — peer connection lifecycle manager
// ======================================================================

use crate::engine::bittorrent::peer::connection::BtPeerConn;
use crate::engine::bittorrent::peer::utp_transport::UtpTransportHandle;
use crate::error::Result;
use crate::network::OutboundNetworkPolicy;
use futures::stream::{self, StreamExt};
use tracing::{debug, info};

/// Maximum time to wait for additional peers after the first successful connection.
pub(crate) const PEER_CONNECT_SETTLE_TIME: std::time::Duration = std::time::Duration::from_secs(1);

/// BT Peer Interaction Manager
///
/// Handles the lifecycle of peer connections from initial connection
/// through the handshake phase until they're ready for data transfer.
pub struct BtPeerInteraction;

impl BtPeerInteraction {
    /// Connect to multiple peers with automatic fallback strategies
    ///
    /// Attempts to connect to all provided peer addresses using:
    /// 1. MSE encryption if required or forced
    /// 2. Plain connection as fallback
    ///
    /// Socket ownership passes to the peer actor immediately after handshake.
    ///
    /// # Arguments
    /// * `peer_addrs` - List of peer addresses to connect to
    /// * `info_hash_raw` - Torrent info hash for handshake
    /// * `num_pieces` - Total number of pieces (for bitfield size)
    /// * `require_crypto` - Whether to require encrypted connections
    /// * `force_encrypt` - Whether to force encryption (fallback to plain)
    ///
    /// # Returns
    /// * `PeerConnectionResult` containing connected peers and failure count
    #[allow(clippy::too_many_arguments)]
    pub(crate) 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,
        connection_options: &BtPeerConnectionOptions,
        utp_transport: Option<UtpTransportHandle>,
        policy: &OutboundNetworkPolicy,
    ) -> PeerConnectionResult {
        info!("[BT] Connecting to {} peers...", peer_addrs.len());

        // A peer can legitimately delay Unchoke while the tracker has already
        // supplied other usable peers. Establish each candidate independently
        // so one slow peer cannot prevent the piece scheduler from starting.
        let mut results = stream::iter(peer_addrs.iter().cloned())
            .map(|addr| {
                let utp_transport = utp_transport.clone();
                async move {
                    debug!("[BT] Connecting to peer {}:{}", addr.ip, addr.port);
                    let result = Self::connect_peer_ready(
                        &addr,
                        info_hash_raw,
                        connection_options,
                        num_pieces,
                        piece_length,
                        total_length,
                        utp_transport.clone(),
                        policy,
                    )
                    .await;
                    (addr, result)
                }
            })
            .buffer_unordered(peer_addrs.len().max(1));

        let mut active_connections = Vec::with_capacity(peer_addrs.len());
        let mut failed_count = 0usize;
        let mut settle_deadline = None;
        loop {
            let next = if let Some(deadline) = settle_deadline {
                tokio::select! {
                    biased;
                    result = results.next() => result,
                    _ = tokio::time::sleep_until(deadline) => break,
                }
            } else {
                results.next().await
            };
            let Some((addr, result)) = next else {
                break;
            };
            match result {
                Ok(conn) => {
                    active_connections.push(conn);
                    settle_deadline.get_or_insert_with(|| {
                        tokio::time::Instant::now() + PEER_CONNECT_SETTLE_TIME
                    });
                }
                Err(e) => {
                    debug!(
                        "[BT] Failed to connect peer {}:{}: {}",
                        addr.ip, addr.port, e
                    );
                    failed_count += 1;
                }
            }
        }

        info!("[BT] Active connections: {}", active_connections.len());

        PeerConnectionResult {
            connections: active_connections,
            failed_count,
        }
    }

    /// Establish and initialize one peer using the same crypto and protocol path
    /// as the initial peer batch.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn connect_peer_ready(
        addr: &aria2_protocol::bittorrent::peer::connection::PeerAddr,
        info_hash_raw: &[u8; 20],
        connection_options: &BtPeerConnectionOptions,
        num_pieces: u32,
        piece_length: u32,
        total_length: u64,
        utp_transport: Option<UtpTransportHandle>,
        policy: &OutboundNetworkPolicy,
    ) -> Result<BtPeerConn> {
        let mut conn = Self::connect_single_peer(
            addr,
            info_hash_raw,
            connection_options,
            utp_transport,
            policy,
        )
        .await?;
        conn.set_timeouts(
            connection_options.keep_alive_interval,
            connection_options.peer_timeout,
        );
        conn.sync_peer_identity();
        conn.allocate_session_resource(piece_length, num_pieces, total_length);
        info!(
            "[BT] Connected to peer {}:{} (encrypted={}, piece_length={}, total_length={})",
            addr.ip,
            addr.port,
            conn.is_encrypted(),
            piece_length,
            total_length
        );
        conn.prepare_actor_startup(
            connection_options.peer_agent.clone(),
            connection_options.listen_port,
            info_hash_raw,
            num_pieces,
        );
        Ok(conn)
    }

    /// Connect to a single peer with encryption fallback logic
    async fn connect_single_peer(
        addr: &aria2_protocol::bittorrent::peer::connection::PeerAddr,
        info_hash_raw: &[u8; 20],
        connection_options: &BtPeerConnectionOptions,
        utp_transport: Option<UtpTransportHandle>,
        policy: &OutboundNetworkPolicy,
    ) -> Result<BtPeerConn> {
        if connection_options.enable_utp
            && !connection_options.crypto.require_mse
            && let Some(utp_transport) = utp_transport.as_ref()
        {
            match addr.to_socket_addr() {
                Ok(endpoint) => {
                    let utp_result = BtPeerConn::connect_utp_with_transport(
                        endpoint,
                        info_hash_raw,
                        connection_options.hybrid_info_hash_v2.as_ref(),
                        &connection_options.local_peer_id,
                        connection_options.connection_timeout,
                        connection_options.dht_enabled,
                        utp_transport,
                    )
                    .await;
                    match utp_result {
                        Ok(conn) => {
                            debug!("[BT] Connected to peer {}:{} over uTP", addr.ip, addr.port);
                            return Ok(conn);
                        }
                        Err(error) => {
                            debug!(
                                "[BT] uTP connection to {}:{} failed, trying TCP: {}",
                                addr.ip, addr.port, error
                            );
                        }
                    }
                }
                Err(error) => {
                    debug!(
                        "[BT] Skipping uTP for peer {}:{} because it is not a numeric IP address: {}",
                        addr.ip, addr.port, error
                    );
                }
            }
        }

        if connection_options.crypto.require_mse {
            // Try MSE encrypted connection
            BtPeerConn::connect_mse_with_policy(
                addr,
                info_hash_raw,
                connection_options.hybrid_info_hash_v2.as_ref(),
                aria2_protocol::bittorrent::peer::mse::MseConnectionOptions {
                    force_encryption: connection_options.crypto.force_encryption,
                    prefer_encryption: connection_options.crypto.prefer_encryption,
                    local_peer_id: connection_options.local_peer_id,
                    timeout: connection_options.connection_timeout,
                    dht_enabled: connection_options.dht_enabled,
                },
                policy,
            )
            .await
        } else {
            // Try MSE first, fall back to plain
            let mse_result = BtPeerConn::connect_mse_with_policy(
                addr,
                info_hash_raw,
                connection_options.hybrid_info_hash_v2.as_ref(),
                aria2_protocol::bittorrent::peer::mse::MseConnectionOptions {
                    force_encryption: connection_options.crypto.force_encryption,
                    prefer_encryption: connection_options.crypto.prefer_encryption,
                    local_peer_id: connection_options.local_peer_id,
                    timeout: connection_options.connection_timeout,
                    dht_enabled: connection_options.dht_enabled,
                },
                policy,
            )
            .await;
            match mse_result {
                Ok(conn) => Ok(conn),
                Err(_) => {
                    debug!("[BT] MSE failed, trying plain connection");
                    BtPeerConn::connect_plain_with_policy(
                        addr,
                        info_hash_raw,
                        connection_options.hybrid_info_hash_v2.as_ref(),
                        &connection_options.local_peer_id,
                        connection_options.connection_timeout,
                        connection_options.dht_enabled,
                        policy,
                    )
                    .await
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{BtPeerConnectionOptions, BtPeerCryptoPolicy, BtPeerInteraction};
    use crate::network::OutboundNetworkPolicy;
    use aria2_protocol::bittorrent::peer::connection::PeerAddr;
    use std::time::Duration;

    #[tokio::test]
    async fn a_slow_peer_does_not_hold_a_ready_peer_batch_open() {
        let info_hash = [7; 20];
        let remote_peer_id = [8; 20];
        let good_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let good_addr = good_listener.local_addr().unwrap();
        let good_server = tokio::spawn(async move {
            loop {
                let (stream, _) = good_listener.accept().await.unwrap();
                if let Ok(incoming) =
                    aria2_protocol::bittorrent::peer::incoming::receive(stream, &[info_hash]).await
                    && let Ok(connection) = incoming.complete(remote_peer_id, None, false).await
                {
                    return connection;
                }
            }
        });

        let slow_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let slow_addr = slow_listener.local_addr().unwrap();
        let slow_server = tokio::spawn(async move {
            while let Ok((stream, _)) = slow_listener.accept().await {
                tokio::spawn(async move {
                    let _stream = stream;
                    tokio::time::sleep(Duration::from_secs(5)).await;
                });
            }
        });

        let options = BtPeerConnectionOptions {
            crypto: BtPeerCryptoPolicy::default(),
            connection_timeout: Duration::from_secs(2),
            keep_alive_interval: Duration::from_secs(120),
            peer_timeout: Duration::from_secs(60),
            local_peer_id: [9; 20],
            peer_agent: "aria2-rust-test".to_string(),
            enable_utp: false,
            utp_listen_port: None,
            dht_enabled: false,
            listen_port: None,
            hybrid_info_hash_v2: None,
        };
        let peers = [
            PeerAddr::new(&good_addr.ip().to_string(), good_addr.port()),
            PeerAddr::new(&slow_addr.ip().to_string(), slow_addr.port()),
        ];

        let result = tokio::time::timeout(
            Duration::from_millis(1500),
            BtPeerInteraction::connect_to_peers(
                &peers,
                &info_hash,
                1,
                16 * 1024,
                3,
                &options,
                None,
                &OutboundNetworkPolicy::direct(),
            ),
        )
        .await
        .expect("the ready peer should be returned before the slow peer times out");

        assert_eq!(result.connections.len(), 1);
        drop(result);
        good_server.abort();
        slow_server.abort();
    }

    #[tokio::test]
    async fn later_peer_success_does_not_extend_the_settle_deadline() {
        let info_hash = [7; 20];
        let remote_peer_id = [8; 20];
        let first_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let first_addr = first_listener.local_addr().unwrap();
        let first_server = tokio::spawn(async move {
            loop {
                let (stream, _) = first_listener.accept().await.unwrap();
                if let Ok(incoming) =
                    aria2_protocol::bittorrent::peer::incoming::receive(stream, &[info_hash]).await
                    && let Ok(connection) = incoming.complete(remote_peer_id, None, false).await
                {
                    return connection;
                }
            }
        });

        let delayed_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let delayed_addr = delayed_listener.local_addr().unwrap();
        let delayed_server = tokio::spawn(async move {
            loop {
                let (stream, _) = delayed_listener.accept().await.unwrap();
                if let Ok(incoming) =
                    aria2_protocol::bittorrent::peer::incoming::receive(stream, &[info_hash]).await
                    && let Ok(connection) = incoming.complete([10; 20], None, false).await
                {
                    return connection;
                }
                // The first connection is the MSE probe. Delay accepting the
                // plaintext retry so this peer becomes ready well inside the
                // first peer's one-second settle window.
                tokio::time::sleep(Duration::from_millis(400)).await;
            }
        });

        let pending_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let pending_addr = pending_listener.local_addr().unwrap();
        let pending_server = tokio::spawn(async move {
            while let Ok((stream, _)) = pending_listener.accept().await {
                tokio::spawn(async move {
                    let _stream = stream;
                    tokio::time::sleep(Duration::from_secs(5)).await;
                });
            }
        });

        let options = BtPeerConnectionOptions {
            crypto: BtPeerCryptoPolicy::default(),
            connection_timeout: Duration::from_secs(2),
            keep_alive_interval: Duration::from_secs(120),
            peer_timeout: Duration::from_secs(60),
            local_peer_id: [9; 20],
            peer_agent: "aria2-rust-test".to_string(),
            enable_utp: false,
            utp_listen_port: None,
            dht_enabled: false,
            listen_port: None,
            hybrid_info_hash_v2: None,
        };
        let peers = [
            PeerAddr::new(&first_addr.ip().to_string(), first_addr.port()),
            PeerAddr::new(&delayed_addr.ip().to_string(), delayed_addr.port()),
            PeerAddr::new(&pending_addr.ip().to_string(), pending_addr.port()),
        ];

        let result = tokio::time::timeout(
            Duration::from_millis(1250),
            BtPeerInteraction::connect_to_peers(
                &peers,
                &info_hash,
                1,
                16 * 1024,
                3,
                &options,
                None,
                &OutboundNetworkPolicy::direct(),
            ),
        )
        .await
        .expect("a later success must not renew the first peer's settle deadline");

        assert_eq!(result.connections.len(), 2);
        drop(result);
        first_server.abort();
        delayed_server.abort();
        pending_server.abort();
    }

    #[tokio::test]
    async fn ipv6_peer_with_utp_enabled_falls_back_to_tcp() {
        let listener = tokio::net::TcpListener::bind("[::1]:0").await.unwrap();
        let endpoint = listener.local_addr().unwrap();
        let info_hash = [7; 20];
        let remote_peer_id = [8; 20];
        let server = tokio::spawn(async move {
            loop {
                let (stream, _) = listener.accept().await.unwrap();
                if let Ok(incoming) =
                    aria2_protocol::bittorrent::peer::incoming::receive(stream, &[info_hash]).await
                    && let Ok(connection) = incoming.complete(remote_peer_id, None, false).await
                {
                    return connection;
                }
            }
        });

        let options = BtPeerConnectionOptions {
            crypto: BtPeerCryptoPolicy::default(),
            connection_timeout: Duration::from_millis(150),
            keep_alive_interval: Duration::from_secs(120),
            peer_timeout: Duration::from_secs(60),
            local_peer_id: [9; 20],
            peer_agent: "aria2-rust-test".to_string(),
            enable_utp: true,
            utp_listen_port: None,
            dht_enabled: false,
            listen_port: None,
            hybrid_info_hash_v2: None,
        };

        let result = BtPeerInteraction::connect_single_peer(
            &PeerAddr::new(&endpoint.ip().to_string(), endpoint.port()),
            &info_hash,
            &options,
            None,
            &OutboundNetworkPolicy::direct(),
        )
        .await;
        if let Err(error) = result {
            server.abort();
            panic!("IPv6 peer connection should fall back from uTP to TCP: {error}");
        }

        server.abort();
    }
}