aria2-core 0.3.7

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
use tracing::{debug, warn};

use crate::error::Result;
use crate::rate_limiter::RateLimiter;
use crate::rate_limiter::RateLimiterConfig;

use crate::engine::bt_message_validation::BtMessageValidator;
use aria2_protocol::bittorrent::message::types::BtMessage;
use aria2_protocol::bittorrent::peer::connection::PeerConnection;
use aria2_protocol::bittorrent::peer::encrypted_connection::EncryptedConnection;

/// Transport variants that can serve upload requests after a torrent is complete.
///
/// Incoming MSE connections must remain encrypted for the whole upload session;
/// converting them to `PeerConnection` would silently drop the crypto state.
pub(crate) enum BtUploadConnection {
    Plain(Box<PeerConnection>),
    Encrypted(Box<EncryptedConnection>),
}

impl BtUploadConnection {
    async fn read_message(&mut self) -> std::result::Result<Option<BtMessage>, String> {
        match self {
            Self::Plain(connection) => connection.read_message().await,
            Self::Encrypted(connection) => connection.read_message().await,
        }
    }

    async fn send_message(&mut self, message: &BtMessage) -> std::result::Result<(), String> {
        match self {
            Self::Plain(connection) => connection.send_message(message).await,
            Self::Encrypted(connection) => connection.send_message(message).await,
        }
    }

    async fn send_choke(&mut self) -> std::result::Result<(), String> {
        match self {
            Self::Plain(connection) => connection.send_choke().await,
            Self::Encrypted(connection) => connection.send_choke().await,
        }
    }

    async fn send_unchoke(&mut self) -> std::result::Result<(), String> {
        match self {
            Self::Plain(connection) => connection.send_unchoke().await,
            Self::Encrypted(connection) => connection.send_unchoke().await,
        }
    }

    fn remote_addr(&self) -> Option<std::net::SocketAddr> {
        match self {
            Self::Plain(connection) => connection.remote_addr(),
            Self::Encrypted(connection) => connection.remote_addr(),
        }
    }

    fn remote_peer_id(&self) -> Option<[u8; 20]> {
        match self {
            Self::Plain(connection) => connection.remote_peer_id,
            Self::Encrypted(connection) => connection.remote_peer_id().copied(),
        }
    }
}

pub trait PieceDataProvider: Send + Sync {
    fn get_piece_data(&self, piece_index: u32, offset: u32, length: u32) -> Option<Vec<u8>>;
    fn has_piece(&self, piece_index: u32) -> bool;
    fn num_pieces(&self) -> u32;
    fn piece_length(&self) -> u32;
}

pub struct BtSeedingConfig {
    pub max_upload_bytes_per_sec: Option<u64>,
    /// Process-wide limiter shared by all download/seeding commands.
    pub global_limiter: Option<RateLimiter>,
    pub max_peers_to_unchoke: usize,
    pub optimistic_unchoke_interval_secs: u64,
}

impl Default for BtSeedingConfig {
    fn default() -> Self {
        Self {
            max_upload_bytes_per_sec: None,
            global_limiter: None,
            max_peers_to_unchoke: 4,
            optimistic_unchoke_interval_secs: 30,
        }
    }
}

pub struct BtUploadSession {
    conn: BtUploadConnection,
    am_choke_state: bool,
    peer_interested: bool,
    uploaded_bytes: u64,
    upload_limiter: Option<RateLimiter>,
    global_upload_limiter: Option<RateLimiter>,
    message_validator: Option<BtMessageValidator>,
    pub(crate) is_dead: bool,
}

impl BtUploadSession {
    pub fn new(conn: PeerConnection, config: &BtSeedingConfig) -> Self {
        Self::new_with_connection(BtUploadConnection::Plain(Box::new(conn)), config)
    }

    pub(crate) fn new_with_connection(conn: BtUploadConnection, config: &BtSeedingConfig) -> Self {
        let upload_limiter = config
            .max_upload_bytes_per_sec
            .filter(|&r| r > 0)
            .map(|r| RateLimiter::new(&RateLimiterConfig::new(None, Some(r))));

        Self {
            conn,
            am_choke_state: false,
            peer_interested: false,
            uploaded_bytes: 0,
            upload_limiter,
            global_upload_limiter: config.global_limiter.clone(),
            message_validator: None,
            is_dead: false,
        }
    }

    pub fn configure_message_validator(&mut self, num_pieces: u32, piece_length: u32) {
        self.message_validator = Some(BtMessageValidator::new(num_pieces, piece_length));
    }

    /// Announce the pieces currently available from this upload peer.
    ///
    /// A leecher must receive availability before it can decide whether to
    /// become interested. This is especially important for peers admitted by
    /// the process-level incoming listener, where no download-side setup
    /// message has been sent yet.
    pub async fn send_piece_availability(
        &mut self,
        provider: &dyn PieceDataProvider,
    ) -> Result<()> {
        let num_pieces = provider.num_pieces();
        if num_pieces == 0 {
            self.conn
                .send_message(&BtMessage::HaveNone)
                .await
                .map_err(|error| {
                    crate::error::Aria2Error::Recoverable(
                        crate::error::RecoverableError::TemporaryNetworkFailure { message: error },
                    )
                })?;
            return Ok(());
        }

        let mut bitfield = vec![0u8; (num_pieces as usize).div_ceil(8)];
        for piece_index in 0..num_pieces {
            if provider.has_piece(piece_index) {
                bitfield[piece_index as usize / 8] |= 1 << (7 - piece_index % 8);
            }
        }
        self.conn
            .send_message(&BtMessage::Bitfield { data: bitfield })
            .await
            .map_err(|error| {
                crate::error::Aria2Error::Recoverable(
                    crate::error::RecoverableError::TemporaryNetworkFailure { message: error },
                )
            })?;
        Ok(())
    }

    pub async fn handle_incoming_messages(
        &mut self,
        provider: &dyn PieceDataProvider,
    ) -> Result<u64> {
        if self.is_dead {
            return Ok(0);
        }

        let round_uploaded = self.uploaded_bytes;

        match self.conn.read_message().await {
            Ok(Some(msg)) => {
                if let Some(validator) = &self.message_validator
                    && let Err(error) = validator.validate(&msg)
                {
                    warn!("Invalid BitTorrent upload message: {}", error);
                    self.is_dead = true;
                    return Ok(self.uploaded_bytes - round_uploaded);
                }
                match msg {
                    BtMessage::Request { request } => {
                        if !self.am_choke_state && self.peer_interested {
                            debug!(
                                "Upload request: piece={}, offset={}, len={}",
                                request.index, request.begin, request.length
                            );

                            let data = provider.get_piece_data(
                                request.index,
                                request.begin,
                                request.length,
                            );
                            if let Some(piece_data) = data {
                                let data_len = piece_data.len() as u64;
                                if let Some(ref lim) = self.upload_limiter {
                                    lim.acquire_upload(data_len).await;
                                }
                                if let Some(ref lim) = self.global_upload_limiter
                                    && lim.is_upload_limited()
                                {
                                    lim.acquire_upload(data_len).await;
                                }
                                self.conn.send_message(&BtMessage::Piece {
                                        index: request.index,
                                        begin: request.begin,
                                        data: piece_data.into(),
                                    }).await.map_err(|e| crate::error::Aria2Error::Recoverable(
                                        crate::error::RecoverableError::TemporaryNetworkFailure { message: e.to_string() }
                                    ))?;
                                self.uploaded_bytes += data_len;
                            } else {
                                warn!(
                                    "No data for piece {} at offset {}",
                                    request.index, request.begin
                                );
                            }
                        } else {
                            debug!(
                                "Ignoring request: choked={} interested={}",
                                self.am_choke_state, self.peer_interested
                            );
                        }
                    }
                    BtMessage::Interested => {
                        self.peer_interested = true;
                        if !self.am_choke_state {
                            self.conn.send_unchoke().await.ok();
                        }
                    }
                    BtMessage::NotInterested => {
                        self.peer_interested = false;
                    }
                    BtMessage::Choke => {
                        debug!("Peer choked us");
                    }
                    BtMessage::Unchoke => {
                        debug!("Peer unchoked us");
                    }
                    BtMessage::Have { piece_index } => {
                        debug!("Peer has piece {}", piece_index);
                    }
                    BtMessage::Cancel { request } => {
                        debug!(
                            "Peer cancelled request for piece {} offset {}",
                            request.index, request.begin
                        );
                    }
                    BtMessage::Piece { .. } => {
                        debug!("Unexpected Piece from peer during seeding");
                    }
                    BtMessage::Bitfield { .. } => {}
                    BtMessage::KeepAlive => {}
                    BtMessage::Port { port: _ } => {}
                    BtMessage::AllowedFast { index } => {
                        debug!("Received AllowedFast for piece {}", index);
                    }
                    BtMessage::Reject {
                        index,
                        offset,
                        length,
                    } => {
                        debug!(
                            "Received Reject for piece {} offset {} len {}",
                            index, offset, length
                        );
                    }
                    BtMessage::Suggest { index } => {
                        debug!("Received Suggest for piece {}", index);
                    }
                    BtMessage::HaveAll => {
                        debug!("Received HaveAll");
                    }
                    BtMessage::HaveNone => {
                        debug!("Received HaveNone");
                    }
                    BtMessage::Extended { ext_id, payload } => {
                        debug!(
                            "Received Extended message: ext_id={}, payload_len={}",
                            ext_id,
                            payload.len()
                        );
                    }
                }
            }
            Ok(None) => {
                debug!("EOF from peer, marking session as dead");
                self.is_dead = true;
                return Ok(self.uploaded_bytes - round_uploaded);
            }
            Err(e) => {
                warn!("Read error from upload peer: {}, marking dead", e);
                self.is_dead = true;
                return Ok(self.uploaded_bytes - round_uploaded);
            }
        }

        Ok(self.uploaded_bytes - round_uploaded)
    }

    pub async fn unchoke_peer(&mut self) -> Result<()> {
        if self.am_choke_state {
            self.conn.send_unchoke().await.map_err(|e| {
                crate::error::Aria2Error::Recoverable(
                    crate::error::RecoverableError::TemporaryNetworkFailure {
                        message: e.to_string(),
                    },
                )
            })?;
            self.am_choke_state = false;
        }
        Ok(())
    }

    pub async fn choke_peer(&mut self) -> Result<()> {
        if !self.am_choke_state {
            self.conn.send_choke().await.map_err(|e| {
                crate::error::Aria2Error::Recoverable(
                    crate::error::RecoverableError::TemporaryNetworkFailure {
                        message: e.to_string(),
                    },
                )
            })?;
            self.am_choke_state = true;
        }
        Ok(())
    }

    pub fn is_peer_choked(&self) -> bool {
        self.am_choke_state
    }

    pub fn is_peer_interested(&self) -> bool {
        self.peer_interested
    }

    pub fn is_dead(&self) -> bool {
        self.is_dead
    }

    pub fn endpoint(&self) -> Option<(String, u16)> {
        self.conn
            .remote_addr()
            .map(|addr| (addr.ip().to_string(), addr.port()))
    }

    pub fn remote_endpoint(&self) -> Option<std::net::SocketAddr> {
        self.conn.remote_addr()
    }

    pub fn remote_peer_id(&self) -> Option<[u8; 20]> {
        self.conn.remote_peer_id()
    }

    pub fn uploaded_bytes(&self) -> u64 {
        self.uploaded_bytes
    }

    pub fn connection_mut(&mut self) -> Option<&mut PeerConnection> {
        match &mut self.conn {
            BtUploadConnection::Plain(connection) => Some(connection),
            BtUploadConnection::Encrypted(_) => None,
        }
    }
}

pub struct InMemoryPieceProvider {
    pieces: Vec<Option<Vec<u8>>>,
    piece_length: u32,
}

impl InMemoryPieceProvider {
    pub fn new(piece_length: u32, num_pieces: u32) -> Self {
        let mut pieces = Vec::with_capacity(num_pieces as usize);
        for _ in 0..num_pieces {
            pieces.push(None);
        }
        Self {
            pieces,
            piece_length,
        }
    }

    pub fn set_piece_data(&mut self, index: u32, data: Vec<u8>) {
        if (index as usize) < self.pieces.len() {
            self.pieces[index as usize] = Some(data);
        }
    }

    pub fn set_all_from_pattern<F>(&mut self, f: F)
    where
        F: Fn(u32, u32) -> u8,
    {
        for i in 0..self.pieces.len() {
            let len = if i == self.pieces.len() - 1 {
                let total = self.piece_length as usize * (self.pieces.len() - 1);
                1024 * 100 - total
            } else {
                self.piece_length as usize
            };
            let mut data = Vec::with_capacity(len);
            for j in 0..len {
                data.push(f(i as u32, j as u32));
            }
            self.pieces[i] = Some(data);
        }
    }
}

impl PieceDataProvider for InMemoryPieceProvider {
    fn get_piece_data(&self, piece_index: u32, offset: u32, length: u32) -> Option<Vec<u8>> {
        let piece = self.pieces.get(piece_index as usize)?.as_ref()?;
        let start = offset as usize;
        let end = (start + length as usize).min(piece.len());
        if start >= piece.len() {
            return None;
        }
        Some(piece[start..end].to_vec())
    }

    fn has_piece(&self, piece_index: u32) -> bool {
        self.pieces
            .get(piece_index as usize)
            .is_some_and(|p| p.is_some())
    }

    fn num_pieces(&self) -> u32 {
        self.pieces.len() as u32
    }

    fn piece_length(&self) -> u32 {
        16 * 1024
    }
}

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

    #[test]
    fn test_seeding_config_default() {
        let cfg = BtSeedingConfig::default();
        assert!(cfg.max_upload_bytes_per_sec.is_none());
        assert_eq!(cfg.max_peers_to_unchoke, 4);
        assert_eq!(cfg.optimistic_unchoke_interval_secs, 30);
    }

    #[test]
    fn test_in_memory_provider_creation() {
        let provider = InMemoryPieceProvider::new(16384, 10);
        assert_eq!(provider.num_pieces(), 10);
        assert!(!provider.has_piece(0));
        assert!(provider.get_piece_data(0, 0, 100).is_none());
    }

    #[test]
    fn test_in_memory_provider_set_and_get() {
        let mut provider = InMemoryPieceProvider::new(256, 4);
        provider.set_piece_data(0, vec![0xAB; 256]);
        provider.set_piece_data(2, vec![0xCD; 128]);

        assert!(provider.has_piece(0));
        assert!(!provider.has_piece(1));
        assert!(provider.has_piece(2));

        let data = provider.get_piece_data(0, 10, 50).unwrap();
        assert_eq!(data.len(), 50);
        assert!(data.iter().all(|&b| b == 0xAB));

        let partial = provider.get_piece_data(2, 100, 28).unwrap();
        assert_eq!(partial.len(), 28);
        assert!(partial.iter().all(|&b| b == 0xCD));
    }

    #[test]
    fn test_in_memory_provider_set_all_from_pattern() {
        let mut provider = InMemoryPieceProvider::new(100, 5);
        provider.set_all_from_pattern(|piece_idx, byte_idx| {
            ((piece_idx * 37 + byte_idx * 13) % 256) as u8
        });

        for i in 0..5u32 {
            assert!(provider.has_piece(i));
            let data = provider.get_piece_data(i, 0, 100).unwrap();
            for (j, &byte) in data.iter().enumerate() {
                assert_eq!(byte, ((i * 37 + j as u32 * 13) % 256) as u8);
            }
        }
    }

    #[test]
    fn test_in_memory_provider_offset_beyond_piece() {
        let mut provider = InMemoryPieceProvider::new(50, 2);
        provider.set_piece_data(0, vec![0x42; 50]);

        assert!(provider.get_piece_data(0, 40, 20).is_some());
        assert!(provider.get_piece_data(0, 60, 10).is_none());
        assert!(provider.get_piece_data(99, 0, 10).is_none());
    }

    #[test]
    fn test_in_memory_provider_last_piece_smaller() {
        let total_size = 260u32;
        let piece_len = 100u32;
        let num_pieces = total_size.div_ceil(piece_len);
        let mut provider = InMemoryPieceProvider::new(piece_len, num_pieces);

        provider.set_all_from_pattern(|_, idx| idx as u8);

        assert!(provider.has_piece(0));
        assert!(provider.has_piece(1));
        assert!(provider.has_piece(2));

        let last_piece = provider.get_piece_data(2, 0, 60).unwrap();
        assert_eq!(last_piece.len(), 60);
    }
}