aria2-core 0.3.13

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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//! File allocation iterator trait and single-file implementations.
//!
//! This module provides an incremental, chunked file allocation API that
//! mirrors the C++ aria2 `FileAllocationIterator` hierarchy:
//!
//! - [`FileAllocationIterator`] — async trait for chunked allocation with
//!   progress reporting
//! - [`SingleFileAllocationIterator`] — zero-fill in 256 KiB chunks
//!   (C++ `SingleFileAllocationIterator`)
//! - [`FallocFileAllocationIterator`] — one-shot `fallocate`/`F_PREALLOCATE`
//!   (C++ `FallocFileAllocationIterator`)
//! - [`TruncFileAllocationIterator`] — `ftruncate`/`SetEndOfFile`
//!   (C++ `TruncFileAllocationIterator`)
//! - [`AdaptiveFileAllocationIterator`] — try `fallocate`, fall back to
//!   zero-fill (C++ `AdaptiveFileAllocationIterator`, default for
//!   `--file-allocation=prealloc`)

use async_trait::async_trait;

use crate::error::Result;
use crate::filesystem::disk_writer::SeekableDiskWriter;
use crate::filesystem::positioned_disk_writer::PositionedDiskWriter;

/// Chunk size for single-file zero-fill allocation.
/// Matches the C++ constant `BUFSIZE = 256_k` (256 KiB).
const BUF_SIZE: usize = 256 * 1024;

/// Async trait for incremental file allocation.
///
/// Callers invoke [`allocate_chunk`] repeatedly until [`finished`] returns
/// `true`. After each call, [`current_length`] and [`total_length`] report
/// progress. This mirrors the C++ `FileAllocationIterator` interface.
///
/// # C++ Reference
///
/// - `FileAllocationIterator.h` — pure virtual base
/// - `allocateChunk()`, `finished()`, `getCurrentLength()`, `getTotalLength()`
#[allow(clippy::double_must_use)]
#[async_trait]
pub trait FileAllocationIterator: Send {
    /// Allocate one chunk of disk space.
    ///
    /// On return, [`current_length`] will have advanced by at most one chunk
    /// worth of bytes.
    async fn allocate_chunk(&mut self) -> Result<()>;

    /// Whether allocation is complete.
    fn finished(&self) -> bool;

    /// Bytes allocated so far.
    fn current_length(&self) -> u64;

    /// Total bytes to allocate.
    fn total_length(&self) -> u64;
}

// =========================================================================
// SingleFileAllocationIterator
// =========================================================================

/// Zero-fill allocation iterator that writes 256 KiB chunks of zeros.
///
/// This is the Rust equivalent of C++ `SingleFileAllocationIterator`.
/// It writes aligned zero buffers at increasing offsets. If the last
/// write overshoots the target length, the file is truncated back to
/// the exact target length.
///
/// This iterator is the fallback when `fallocate` is not available or
/// not supported by the filesystem.
pub struct SingleFileAllocationIterator {
    writer: PositionedDiskWriter,
    offset: u64,
    total_length: u64,
    /// Zero-fill buffer (reused across chunks). Allocated on first use.
    buffer: Option<Vec<u8>>,
}

impl SingleFileAllocationIterator {
    /// Create a new single-file allocation iterator.
    ///
    /// # Arguments
    /// * `writer` — positioned writer for the file (must be open)
    /// * `offset` — starting offset (current file size, typically 0)
    /// * `total_length` — target file size
    pub fn new(writer: PositionedDiskWriter, offset: u64, total_length: u64) -> Self {
        Self {
            writer,
            offset,
            total_length,
            buffer: None,
        }
    }

    /// Initialize the zero-fill buffer. Must be called before
    /// `allocate_chunk()`. This is the Rust equivalent of the C++ `init()`
    /// method which allocates the aligned buffer.
    pub fn init(&mut self) {
        if self.buffer.is_none() {
            self.buffer = Some(vec![0u8; BUF_SIZE]);
        }
    }

    /// Get a mutable reference to the positioned writer.
    pub fn writer_mut(&mut self) -> &mut PositionedDiskWriter {
        &mut self.writer
    }

    /// Recover the owned writer after allocation has completed.
    pub fn into_inner(self) -> PositionedDiskWriter {
        self.writer
    }
}

#[async_trait]
impl FileAllocationIterator for SingleFileAllocationIterator {
    async fn allocate_chunk(&mut self) -> Result<()> {
        let buf = self.buffer.as_deref().unwrap_or_else(|| {
            static EMPTY: &[u8] = &[0u8; BUF_SIZE];
            EMPTY
        });

        self.writer.write_at(self.offset, buf).await?;
        self.offset += BUF_SIZE as u64;

        // If we wrote past the target length, truncate back.
        if self.total_length < self.offset {
            self.writer.truncate(self.total_length).await?;
            self.offset = self.total_length;
        }

        Ok(())
    }

    fn finished(&self) -> bool {
        self.offset >= self.total_length
    }

    fn current_length(&self) -> u64 {
        self.offset.min(self.total_length)
    }

    fn total_length(&self) -> u64 {
        self.total_length
    }
}

// =========================================================================
// FallocFileAllocationIterator
// =========================================================================

/// Fast allocation iterator using `fallocate` / `F_PREALLOCATE` /
/// `SetFileValidData`.
///
/// This is the Rust equivalent of C++ `FallocFileAllocationIterator`.
/// It completes in a single `allocate_chunk()` call by invoking the
/// platform-native preallocation syscall on the underlying positioned writer.
///
/// On Linux, this calls `fallocate(2)` which allocates zeroed blocks.
/// On macOS, this calls `fcntl(F_PREALLOCATE)` which may not zero-fill.
/// On Windows, this calls `SetFileValidData` which does not zero-fill.
pub struct FallocFileAllocationIterator {
    writer: PositionedDiskWriter,
    offset: u64,
    total_length: u64,
    secure_falloc: bool,
    done: bool,
}

impl FallocFileAllocationIterator {
    /// Create a new falloc iterator.
    ///
    /// # Arguments
    /// * `writer` — positioned writer for allocation operations (must have an open
    ///   file with a raw fd/handle available)
    /// * `offset` — current file size
    /// * `total_length` — target file size
    pub fn new(writer: PositionedDiskWriter, offset: u64, total_length: u64) -> Self {
        Self::new_with_secure_falloc(writer, offset, total_length, false)
    }

    /// Create a fallocate iterator with the platform security policy used by
    /// `--secure-falloc`.
    pub fn new_with_secure_falloc(
        writer: PositionedDiskWriter,
        offset: u64,
        total_length: u64,
        secure_falloc: bool,
    ) -> Self {
        Self {
            writer,
            offset,
            total_length,
            secure_falloc,
            done: false,
        }
    }

    /// Get a mutable reference to the positioned writer.
    pub fn writer_mut(&mut self) -> &mut PositionedDiskWriter {
        &mut self.writer
    }

    /// Recover the owned writer after allocation has completed.
    pub fn into_inner(self) -> PositionedDiskWriter {
        self.writer
    }
}

#[async_trait]
impl FileAllocationIterator for FallocFileAllocationIterator {
    async fn allocate_chunk(&mut self) -> Result<()> {
        if self.offset < self.total_length {
            // Use the full allocation pipeline which handles
            // platform-specific fallocate with fallbacks.
            let length = self.total_length;
            crate::filesystem::file_allocation::allocate_file(
                &mut self.writer,
                length,
                crate::filesystem::file_allocation::AllocationStrategy::Falloc,
                self.secure_falloc,
            )
            .await?;
            self.offset = self.total_length;
        } else {
            // File is already at least total_length; just ensure size is exact.
            self.writer.truncate(self.total_length).await?;
            self.offset = self.total_length;
        }
        self.done = true;
        Ok(())
    }

    fn finished(&self) -> bool {
        self.done
    }

    fn current_length(&self) -> u64 {
        self.offset
    }

    fn total_length(&self) -> u64 {
        self.total_length
    }
}

// =========================================================================
// TruncFileAllocationIterator
// =========================================================================

/// Truncation-based allocation iterator using `ftruncate` / `SetEndOfFile`.
///
/// This is the Rust equivalent of C++ `TruncFileAllocationIterator`.
/// It completes in a single `allocate_chunk()` call by truncating the
/// file to the target length. This creates a sparse file — blocks are
/// not physically allocated until written.
pub struct TruncFileAllocationIterator {
    writer: PositionedDiskWriter,
    offset: u64,
    total_length: u64,
    done: bool,
}

impl TruncFileAllocationIterator {
    /// Create a new truncation iterator.
    ///
    /// # Arguments
    /// * `writer` — positioned writer for truncation (must have an open file)
    /// * `offset` — current file size
    /// * `total_length` — target file size
    pub fn new(writer: PositionedDiskWriter, offset: u64, total_length: u64) -> Self {
        Self {
            writer,
            offset,
            total_length,
            done: false,
        }
    }

    /// Get a mutable reference to the positioned writer.
    pub fn writer_mut(&mut self) -> &mut PositionedDiskWriter {
        &mut self.writer
    }
}

#[async_trait]
impl FileAllocationIterator for TruncFileAllocationIterator {
    async fn allocate_chunk(&mut self) -> Result<()> {
        // C++ TruncFileAllocationIterator calls stream->allocate(0, totalLength_, true)
        // which maps to ftruncate. In Rust we use set_len via truncate().
        self.writer.truncate(self.total_length).await?;
        // Flush to ensure metadata is persisted before the caller checks file size.
        self.writer.flush().await?;
        self.offset = self.total_length;
        self.done = true;
        Ok(())
    }

    fn finished(&self) -> bool {
        self.done
    }

    fn current_length(&self) -> u64 {
        self.offset
    }

    fn total_length(&self) -> u64 {
        self.total_length
    }
}

// =========================================================================
// AdaptiveFileAllocationIterator
// =========================================================================

/// Adaptive allocation iterator that tries `fallocate` first, then falls back
/// to zero-fill.
///
/// This is the Rust equivalent of C++ `AdaptiveFileAllocationIterator` and is
/// the default iterator for `--file-allocation=prealloc`.
///
/// Strategy:
/// 1. On first `allocate_chunk()`, try a small (4 KiB) `fallocate` probe.
/// 2. If it succeeds, switch to `FallocFileAllocationIterator` for the rest.
/// 3. If it fails (e.g. `EOPNOTSUPP`), switch to
///    `SingleFileAllocationIterator` (zero-fill).
///
/// On platforms without `fallocate` (or when no raw fd is available),
/// the zero-fill path is used directly.
pub struct AdaptiveFileAllocationIterator {
    writer: Option<PositionedDiskWriter>,
    offset: u64,
    total_length: u64,
    secure_falloc: bool,
    /// Inner iterator selected after the fallocate probe.
    inner: Option<AdaptiveInner>,
}

/// Inner iterator variant after the adaptive probe decides the strategy.
enum AdaptiveInner {
    Falloc(FallocFileAllocationIterator),
    Single(SingleFileAllocationIterator),
}

impl AdaptiveFileAllocationIterator {
    /// Create a new adaptive iterator.
    ///
    /// # Arguments
    /// * `writer` — positioned writer (must have an open file)
    /// * `offset` — current file size
    /// * `total_length` — target file size
    pub fn new(writer: PositionedDiskWriter, offset: u64, total_length: u64) -> Self {
        Self::new_with_secure_falloc(writer, offset, total_length, false)
    }

    /// Create an adaptive iterator with the platform security policy used by
    /// `--secure-falloc`.
    pub fn new_with_secure_falloc(
        writer: PositionedDiskWriter,
        offset: u64,
        total_length: u64,
        secure_falloc: bool,
    ) -> Self {
        Self {
            writer: Some(writer),
            offset,
            total_length,
            secure_falloc,
            inner: None,
        }
    }

    /// Try the fallocate probe and select the inner strategy.
    ///
    /// On Linux, we call `fallocate(2)` on a small 4 KiB region.
    /// If it succeeds, the filesystem supports fallocate and we use
    /// `FallocFileAllocationIterator`. If it returns `EOPNOTSUPP`,
    /// we fall back to `SingleFileAllocationIterator` (zero-fill).
    ///
    /// On non-Linux platforms where fallocate is not available or
    /// the raw fd is missing, we go directly to zero-fill.
    async fn probe_and_select(&mut self) -> Result<()> {
        // Probe: try a small fallocate (4 KiB).
        let probe_len = 4 * 1024u64;
        let remaining = self.total_length.saturating_sub(self.offset);
        let probe_len = probe_len.min(remaining);

        if probe_len == 0 {
            // Nothing to allocate.
            return Ok(());
        }

        // Try the fallocate path. We use the file_allocation::allocate_file
        // function which handles platform-specific fallocate with EOPNOTSUPP
        // fallback.
        let probe_result = crate::filesystem::file_allocation::allocate_file(
            self.writer.as_mut().expect("adaptive writer is present"),
            self.offset + probe_len,
            crate::filesystem::file_allocation::AllocationStrategy::Falloc,
            self.secure_falloc,
        )
        .await;

        match probe_result {
            Ok(()) => {
                // fallocate succeeded — filesystem supports it.
                // The probe already allocated up to offset + probe_len.
                self.offset += probe_len;
                if self.offset >= self.total_length {
                    // Small file, fully allocated by the probe.
                    return Ok(());
                }
                // Continue with fallocate for the remaining region.
                self.inner = Some(AdaptiveInner::Falloc(
                    FallocFileAllocationIterator::new_with_secure_falloc(
                        self.writer.take().expect("adaptive writer is present"),
                        self.offset,
                        self.total_length,
                        self.secure_falloc,
                    ),
                ));
            }
            Err(_) => {
                // fallocate failed — fall back to zero-fill.
                tracing::debug!("Adaptive: fallocate probe failed, falling back to zero-fill");
                let mut single = SingleFileAllocationIterator::new(
                    self.writer.take().expect("adaptive writer is present"),
                    self.offset,
                    self.total_length,
                );
                single.init();
                self.inner = Some(AdaptiveInner::Single(single));
            }
        }

        Ok(())
    }
}

#[async_trait]
impl FileAllocationIterator for AdaptiveFileAllocationIterator {
    async fn allocate_chunk(&mut self) -> Result<()> {
        if self.inner.is_none() {
            self.probe_and_select().await?;
        }

        match &mut self.inner {
            Some(AdaptiveInner::Falloc(falloc)) => falloc.allocate_chunk().await,
            Some(AdaptiveInner::Single(single)) => single.allocate_chunk().await,
            None => {
                // probe_and_select determined nothing to allocate.
                Ok(())
            }
        }
    }

    fn finished(&self) -> bool {
        match &self.inner {
            Some(AdaptiveInner::Falloc(falloc)) => falloc.finished(),
            Some(AdaptiveInner::Single(single)) => single.finished(),
            None => self.offset >= self.total_length,
        }
    }

    fn current_length(&self) -> u64 {
        match &self.inner {
            Some(AdaptiveInner::Falloc(falloc)) => falloc.current_length(),
            Some(AdaptiveInner::Single(single)) => single.current_length(),
            None => self.offset,
        }
    }

    fn total_length(&self) -> u64 {
        self.total_length
    }
}

impl AdaptiveFileAllocationIterator {
    /// Recover the owned writer after allocation has completed.
    pub fn into_inner(self) -> PositionedDiskWriter {
        match self.inner {
            Some(AdaptiveInner::Falloc(iterator)) => iterator.into_inner(),
            Some(AdaptiveInner::Single(iterator)) => iterator.into_inner(),
            None => self.writer.expect("adaptive writer is present"),
        }
    }

    /// Close the file held by the selected inner iterator.
    pub async fn close(&mut self) -> Result<()> {
        match &mut self.inner {
            Some(AdaptiveInner::Falloc(iterator)) => {
                iterator
                    .writer_mut()
                    .close_without_sync("adaptive allocation close")
                    .await
            }
            Some(AdaptiveInner::Single(iterator)) => {
                iterator
                    .writer_mut()
                    .close_without_sync("adaptive allocation close")
                    .await
            }
            None => {
                self.writer
                    .as_mut()
                    .expect("adaptive writer is present")
                    .close_without_sync("adaptive allocation close")
                    .await
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::filesystem::positioned_disk_writer::PositionedDiskWriter;
    #[tokio::test]
    async fn test_trunc_iterator_completes_in_one_chunk() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test_trunc_iter.bin");

        let mut adaptor = PositionedDiskWriter::new(&path, None);
        adaptor.open().await.unwrap();

        let mut iter = TruncFileAllocationIterator::new(adaptor, 0, 4096);
        assert!(!iter.finished());
        iter.allocate_chunk().await.unwrap();
        assert!(iter.finished());
        assert_eq!(iter.current_length(), 4096);
        assert_eq!(iter.total_length(), 4096);

        // Verify file size
        let meta = tokio::fs::metadata(&path).await.unwrap();
        assert_eq!(meta.len(), 4096);
    }

    #[tokio::test]
    async fn test_single_file_iterator_chunked_allocation() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test_single_iter.bin");

        let mut adaptor = PositionedDiskWriter::new(&path, None);
        adaptor.open().await.unwrap();
        adaptor.truncate(0).await.unwrap();

        // Allocate 512 KiB (2 chunks of 256 KiB)
        let mut iter = SingleFileAllocationIterator::new(adaptor, 0, 512 * 1024);
        iter.init();

        assert!(!iter.finished());
        iter.allocate_chunk().await.unwrap();
        assert!(!iter.finished());
        assert_eq!(iter.current_length(), 256 * 1024);

        iter.allocate_chunk().await.unwrap();
        assert!(iter.finished());
        assert_eq!(iter.current_length(), 512 * 1024);
    }

    #[tokio::test]
    async fn test_single_file_iterator_truncates_overshoot() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test_overshoot.bin");

        let mut adaptor = PositionedDiskWriter::new(&path, None);
        adaptor.open().await.unwrap();
        adaptor.truncate(0).await.unwrap();

        // 1 byte more than a single chunk — second write overshoots
        let target = BUF_SIZE as u64 + 1;
        let mut iter = SingleFileAllocationIterator::new(adaptor, 0, target);
        iter.init();

        iter.allocate_chunk().await.unwrap();
        assert!(!iter.finished());

        iter.allocate_chunk().await.unwrap();
        assert!(iter.finished());
        assert_eq!(iter.current_length(), target);
    }

    #[tokio::test]
    async fn test_adaptive_iterator_fallback_to_zero_fill() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test_adaptive.bin");

        let mut adaptor = PositionedDiskWriter::new(&path, None);
        adaptor.open().await.unwrap();
        adaptor.truncate(0).await.unwrap();

        // On any platform, adaptive should complete allocation.
        let mut iter = AdaptiveFileAllocationIterator::new(adaptor, 0, 1024 * 1024);
        while !iter.finished() {
            iter.allocate_chunk().await.unwrap();
        }

        assert_eq!(iter.current_length(), 1024 * 1024);
    }

    #[tokio::test]
    async fn test_trunc_iterator_with_existing_offset() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test_trunc_existing.bin");

        // Pre-create a file with some content
        tokio::fs::write(&path, b"hello").await.unwrap();

        let mut adaptor = PositionedDiskWriter::new(&path, None);
        adaptor.open().await.unwrap();

        let mut iter = TruncFileAllocationIterator::new(adaptor, 5, 1024);
        iter.allocate_chunk().await.unwrap();
        assert!(iter.finished());
        assert_eq!(iter.current_length(), 1024);
    }
}