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
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
525
526
527
528
use crate::error::{Aria2Error, Result};
use std::path::{Path, PathBuf};

mod native;
mod persistence;

/// Block size of an in-flight piece's bitfield, as in aria2.
const IN_FLIGHT_BLOCK_LENGTH: u64 = 16 * 1024;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ControlFileInFlightPiece {
    pub index: u32,
    pub length: u32,
    pub bitfield: Vec<u8>,
}

#[derive(Debug, Clone)]
pub struct ControlFile {
    path: PathBuf,
    total_length: u64,
    completed_length: u64,
    upload_length: u64,
    bitfield: Vec<u8>,
    in_flight_pieces: Vec<ControlFileInFlightPiece>,
    num_pieces: usize,
    checksum_algo: u8,
    checksum_value: Vec<u8>,
    torrent_checkpoint: bool,
    torrent_info_hash: Option<[u8; 20]>,
    torrent_piece_length: Option<u32>,
    native_piece_length: Option<u32>,
    native_layout: bool,
}

impl ControlFile {
    pub fn path(&self) -> &Path {
        &self.path
    }
    pub fn total_length(&self) -> u64 {
        self.total_length
    }

    /// Piece length explicitly represented by this native checkpoint layout.
    ///
    /// Legacy A2CF checkpoints did not store a generic piece length, so they
    /// return `None` and must not be interpreted using a new segment layout.
    pub fn piece_length(&self) -> Option<u32> {
        self.native_piece_length.or(self.torrent_piece_length)
    }
    pub fn completed_length(&self) -> u64 {
        self.completed_length
    }
    pub fn bitfield(&self) -> &[u8] {
        &self.bitfield
    }

    pub fn in_flight_pieces(&self) -> &[ControlFileInFlightPiece] {
        &self.in_flight_pieces
    }

    pub fn set_in_flight_pieces(&mut self, pieces: Vec<ControlFileInFlightPiece>) {
        self.in_flight_pieces = pieces;
    }
    pub fn set_checksum(&mut self, algo: u8, value: Vec<u8>) {
        self.checksum_algo = algo;
        self.checksum_value = value;
    }
    pub fn checksum_algo(&self) -> u8 {
        self.checksum_algo
    }

    pub fn checksum_value(&self) -> &[u8] {
        &self.checksum_value
    }

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

    /// Whether this value was decoded from aria2's native v0/v1 layout.
    pub fn uses_native_layout(&self) -> bool {
        self.native_layout
    }

    /// Mark this Rust-owned checkpoint as BitTorrent state.
    ///
    /// The marker prevents a generic HTTP/FTP checkpoint with the same output
    /// path and shape from being mistaken for verified torrent pieces.
    pub fn mark_torrent_checkpoint(&mut self) {
        self.torrent_checkpoint = true;
    }

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

    /// Store the torrent identity for a Rust-owned BitTorrent checkpoint.
    pub fn set_torrent_info_hash(&mut self, info_hash: [u8; 20]) {
        self.torrent_info_hash = Some(info_hash);
    }

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

    /// Store the piece length used by a Rust-owned BitTorrent checkpoint.
    pub fn set_torrent_piece_length(&mut self, piece_length: u32) {
        self.torrent_piece_length = Some(piece_length);
    }

    pub fn torrent_piece_length(&self) -> Option<u32> {
        self.torrent_piece_length
    }

    /// Replace the persisted piece bitfield with a complete snapshot.
    pub fn set_bitfield(&mut self, bitfield: Vec<u8>) {
        self.bitfield = bitfield;
    }

    pub(crate) fn normalize_legacy_piece_layout(&mut self, num_pieces: usize) -> Result<()> {
        if !self.native_layout {
            self.normalize_bitfield(num_pieces)?;
        }
        Ok(())
    }

    pub async fn open_or_create(
        ctrl_path: &Path,
        total_length: u64,
        num_pieces: usize,
    ) -> Result<Self> {
        if ctrl_path.exists() {
            let mut control_file = Self::load(ctrl_path).await?.ok_or_else(|| {
                Aria2Error::FileIo(format!(
                    "Failed to load control file: {}",
                    ctrl_path.display()
                ))
            })?;
            // Legacy A2CF has no official piece-length field, so restore its
            // logical layout at the typed open seam. Native files retain the
            // piece layout encoded by aria2 itself.
            if !control_file.native_layout {
                control_file.normalize_bitfield(num_pieces)?;
            }
            Ok(control_file)
        } else {
            let piece_length = piece_length_for(total_length, num_pieces)?;
            Self::new_with_piece_length(ctrl_path, total_length, piece_length)
        }
    }

    /// Open an existing checkpoint only when it uses this exact fixed-piece
    /// layout, or create a new checkpoint with the supplied piece length.
    pub async fn open_or_create_with_piece_length(
        ctrl_path: &Path,
        total_length: u64,
        piece_length: u32,
    ) -> Result<Self> {
        if piece_length == 0 {
            return Err(Aria2Error::InvalidArgument(
                "Control file piece length must not be 0".to_string(),
            ));
        }
        if ctrl_path.exists() {
            let control_file = Self::load(ctrl_path).await?.ok_or_else(|| {
                Aria2Error::FileIo(format!(
                    "Failed to load control file: {}",
                    ctrl_path.display()
                ))
            })?;
            let expected_pieces = piece_count(total_length, piece_length)?;
            if control_file.total_length() == total_length
                && control_file.piece_length() == Some(piece_length)
                && control_file.bitfield().len() == expected_pieces.div_ceil(8)
            {
                return Ok(control_file);
            }
            return Err(Aria2Error::InvalidArgument(format!(
                "Control file layout does not match piece length {}: {}",
                piece_length,
                ctrl_path.display()
            )));
        }
        Self::new_with_piece_length(ctrl_path, total_length, piece_length)
    }

    fn new_with_piece_length(
        ctrl_path: &Path,
        total_length: u64,
        piece_length: u32,
    ) -> Result<Self> {
        let actual_num_pieces = piece_count(total_length, piece_length)?;
        let bitfield_len = actual_num_pieces.div_ceil(8);
        Ok(Self {
            path: ctrl_path.to_path_buf(),
            total_length,
            completed_length: 0,
            upload_length: 0,
            bitfield: vec![0u8; bitfield_len],
            in_flight_pieces: Vec::new(),
            num_pieces: actual_num_pieces,
            checksum_algo: 0,
            checksum_value: Vec::new(),
            torrent_checkpoint: false,
            torrent_info_hash: None,
            torrent_piece_length: None,
            native_piece_length: Some(piece_length),
            native_layout: false,
        })
    }

    pub fn mark_piece_done(&mut self, index: usize) {
        let byte_index = index / 8;
        let bit_index = index % 8;
        if index < self.num_pieces && byte_index < self.bitfield.len() {
            self.bitfield[byte_index] |= 1 << (7 - bit_index);
            self.in_flight_pieces
                .retain(|piece| piece.index as usize != index);
            self.completed_length = self.calculate_completed();
        }
    }

    fn normalize_bitfield(&mut self, num_pieces: usize) -> Result<()> {
        let piece_length = piece_length_for(self.total_length, num_pieces)?;
        self.native_piece_length = Some(piece_length);
        self.num_pieces = piece_count(self.total_length, piece_length)?;
        self.bitfield.resize(self.num_pieces.div_ceil(8), 0);

        if let Some(last_byte) = self.bitfield.last_mut() {
            let valid_bits = self.num_pieces % 8;
            if valid_bits != 0 {
                *last_byte &= u8::MAX << (8 - valid_bits);
            }
        }

        self.completed_length = self.calculate_completed();
        Ok(())
    }

    pub fn is_piece_done(&self, index: usize) -> bool {
        let byte_index = index / 8;
        let bit_index = index % 8;
        if byte_index < self.bitfield.len() {
            (self.bitfield[byte_index] & (1 << (7 - bit_index))) != 0
        } else {
            false
        }
    }

    pub fn completed_pieces(&self) -> usize {
        self.bitfield.iter().map(|b| b.count_ones() as usize).sum()
    }

    fn calculate_completed(&self) -> u64 {
        if self.total_length == 0 || self.num_pieces == 0 {
            return 0;
        }
        let piece_size = self
            .torrent_piece_length
            .or(self.native_piece_length)
            .map(u64::from)
            .unwrap_or_else(|| self.total_length.div_ceil(self.num_pieces as u64));
        (0..self.num_pieces)
            .filter(|&index| self.is_piece_done(index))
            .map(|index| {
                let offset = index as u64 * piece_size;
                self.total_length.saturating_sub(offset).min(piece_size)
            })
            .sum()
    }

    pub fn update_completed_length(&mut self, length: u64) {
        self.completed_length = length.min(self.total_length);
    }

    /// Offset and length of piece `index`.
    fn piece_span(&self, index: usize) -> Option<(u64, u64)> {
        let piece_length = u64::from(self.effective_piece_length().ok()?);
        let offset = (index as u64).checked_mul(piece_length)?;
        (index < self.num_pieces && offset < self.total_length)
            .then(|| (offset, piece_length.min(self.total_length - offset)))
    }

    /// Bytes of an unfinished piece written from its start, per its in-flight
    /// block bitfield (aria2's 16 KiB blocks).
    fn in_flight_prefix(&self, index: usize) -> u64 {
        let Some(piece) = self
            .in_flight_pieces
            .iter()
            .find(|piece| piece.index as usize == index)
        else {
            return 0;
        };
        let blocks = (0..piece.bitfield.len() * 8)
            .take_while(|&block| piece.bitfield[block / 8] & (1 << (7 - block % 8)) != 0)
            .count() as u64;
        blocks
            .saturating_mul(IN_FLIGHT_BLOCK_LENGTH)
            .min(u64::from(piece.length))
    }

    /// Record `written` bytes from the start of piece `index` as in flight.
    /// Only whole blocks count, and a recorded prefix is never lowered.
    fn set_in_flight_prefix(&mut self, index: usize, written: u64) {
        let Some((_, length)) = self.piece_span(index) else {
            return;
        };
        let block_count = length.div_ceil(IN_FLIGHT_BLOCK_LENGTH);
        let blocks = if written >= length {
            block_count
        } else {
            written / IN_FLIGHT_BLOCK_LENGTH
        };
        if self.is_piece_done(index)
            || blocks == 0
            || blocks.saturating_mul(IN_FLIGHT_BLOCK_LENGTH).min(length)
                <= self.in_flight_prefix(index)
        {
            return;
        }
        let (Ok(piece_index), Ok(piece_length)) = (u32::try_from(index), u32::try_from(length))
        else {
            return;
        };
        let mut bitfield = vec![0u8; block_count.div_ceil(8) as usize];
        for block in 0..blocks as usize {
            bitfield[block / 8] |= 1 << (7 - block % 8);
        }
        let record = ControlFileInFlightPiece {
            index: piece_index,
            length: piece_length,
            bitfield,
        };
        match self
            .in_flight_pieces
            .iter_mut()
            .find(|piece| piece.index as usize == index)
        {
            Some(existing) => *existing = record,
            None => self.in_flight_pieces.push(record),
        }
    }

    /// Record that `[start, start + length)` of an HTTP/FTP download is on
    /// disk. Pieces it covers are marked done; a piece it fills from its
    /// start, or from where that piece's in-flight prefix ends, gets a longer
    /// in-flight prefix. A one-piece (sequential) checkpoint keeps a prefix in
    /// `completed_length` instead.
    pub fn record_completed_range(&mut self, start: u64, length: u64) {
        let end = start.saturating_add(length).min(self.total_length);
        if start >= end {
            return;
        }
        if self.num_pieces <= 1 {
            if start <= self.completed_length {
                self.completed_length = self.completed_length.max(end);
            }
            return;
        }
        let Ok(piece_length) = self.effective_piece_length().map(u64::from) else {
            return;
        };
        for index in (start / piece_length) as usize..end.div_ceil(piece_length) as usize {
            let Some((offset, span)) = self.piece_span(index) else {
                break;
            };
            if self.is_piece_done(index)
                || (offset < start && self.in_flight_prefix(index) < start - offset)
            {
                continue;
            }
            if end >= offset + span {
                self.mark_piece_done(index);
            } else {
                self.set_in_flight_prefix(index, end - offset);
            }
        }
        self.recount_completed();
    }

    /// Record that the first `length` bytes are on disk, as a sequential
    /// download writes them. A split checkpoint gets pieces marked, because a
    /// concurrent resume reads only its bitfield and in-flight pieces.
    pub fn record_completed_prefix(&mut self, length: u64) {
        if self.num_pieces <= 1 {
            self.update_completed_length(length);
        } else {
            self.record_completed_range(0, length);
        }
    }

    /// Set `completed_length` to the finished pieces plus in-flight prefixes.
    fn recount_completed(&mut self) {
        let in_flight: u64 = self
            .in_flight_pieces
            .iter()
            .filter(|piece| !self.is_piece_done(piece.index as usize))
            .map(|piece| self.in_flight_prefix(piece.index as usize))
            .sum();
        self.completed_length = (self.calculate_completed() + in_flight).min(self.total_length);
    }

    fn effective_piece_length(&self) -> Result<u32> {
        self.torrent_piece_length
            .or(self.native_piece_length)
            .or_else(|| piece_length_for(self.total_length, self.num_pieces).ok())
            .filter(|piece_length| *piece_length != 0)
            .ok_or_else(|| {
                Aria2Error::InvalidArgument(
                    "Control file piece length cannot be represented".to_string(),
                )
            })
    }

    pub fn control_path_for(output_path: &Path) -> PathBuf {
        // aria2 appends the suffix.  Replacing the extension would turn
        // `file.tar.gz` into `file.tar.aria2`, while the documented sidecar
        // is `file.tar.gz.aria2`.  The same rule applies to a multi-file
        // torrent's top directory (`top-directory.aria2`).
        if output_path == Path::new(".") || output_path == Path::new("..") {
            return output_path.join(".aria2");
        }

        let Some(file_name) = output_path.file_name() else {
            return output_path.join(".aria2");
        };
        let mut control_name = file_name.to_os_string();
        control_name.push(".aria2");
        output_path.with_file_name(control_name)
    }
}

pub(super) fn checksum_length(algo: u8) -> Option<usize> {
    match algo {
        1 => Some(16), // MD5
        2 => Some(20), // SHA-1
        3 => Some(32), // SHA-256
        4 => Some(8),  // CRC-64
        _ => None,
    }
}

pub(super) fn piece_length_for(total_length: u64, num_pieces: usize) -> Result<u32> {
    let divisor = num_pieces.max(1) as u64;
    let piece_length = if total_length == 0 {
        1
    } else {
        total_length.div_ceil(divisor)
    };
    u32::try_from(piece_length).map_err(|_| {
        Aria2Error::InvalidArgument(format!(
            "Control file piece length exceeds native aria2 limit: {}",
            piece_length
        ))
    })
}

pub(super) fn piece_count(total_length: u64, piece_length: u32) -> Result<usize> {
    if piece_length == 0 {
        return Err(Aria2Error::InvalidArgument(
            "Control file piece length must not be 0".to_string(),
        ));
    }
    usize::try_from(total_length.div_ceil(piece_length as u64))
        .map_err(|_| Aria2Error::InvalidArgument("Control file has too many pieces".to_string()))
}

pub(super) fn validate_in_flight_pieces(
    pieces: &[ControlFileInFlightPiece],
    total_length: u64,
    piece_length: u32,
    num_pieces: usize,
    _completed_bitfield: &[u8],
) -> Result<()> {
    let mut seen = std::collections::HashSet::with_capacity(pieces.len());
    for piece in pieces {
        let index = piece.index as usize;
        if index >= num_pieces {
            return Err(Aria2Error::FileIo(format!(
                "In-flight torrent piece index is out of range: {}",
                piece.index
            )));
        }
        if !seen.insert(piece.index) {
            return Err(Aria2Error::FileIo(format!(
                "Duplicate in-flight torrent piece index: {}",
                piece.index
            )));
        }
        if piece.length == 0 || piece.length > piece_length {
            return Err(Aria2Error::FileIo(format!(
                "In-flight torrent piece length is out of range: {}",
                piece.length
            )));
        }
        let block_count = (piece.length as usize).div_ceil(16 * 1024);
        let expected_bitfield_length = block_count.div_ceil(8);
        if piece.bitfield.len() != expected_bitfield_length {
            return Err(Aria2Error::FileIo(format!(
                "In-flight block bitfield length mismatch: expected {}, actual {}",
                expected_bitfield_length,
                piece.bitfield.len()
            )));
        }
        let unused_bits = (8 - block_count % 8) % 8;
        if unused_bits != 0
            && piece
                .bitfield
                .last()
                .is_some_and(|byte| byte & ((1u8 << unused_bits) - 1) != 0)
        {
            return Err(Aria2Error::FileIo(
                "In-flight block bitfield has set trailing bits".to_string(),
            ));
        }
        let piece_offset = u64::from(piece.index) * u64::from(piece_length);
        if piece_offset >= total_length {
            return Err(Aria2Error::FileIo(format!(
                "In-flight torrent piece offset is out of range: {}",
                piece.index
            )));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests;