aria2-core 0.3.10

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
//! Active output path registry — prevents silent filename collisions between concurrent downloads.
//!
//! When multiple `DownloadCommand` instances target the same output directory with the same
//! inferred filename, the last writer would silently overwrite previous results. This module
//! provides a process-wide registry that detects such collisions and automatically appends
//! a `.N` suffix (aria2-compatible style) to produce unique filenames.

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use tracing::{debug, info, warn};

use crate::error::{Aria2Error, Result};
use crate::filesystem::control_file::ControlFile;

const MAX_OUTPUT_FILENAME_BYTES: usize = 255;

/// Compatibility policy used when selecting a local output path.
///
/// This captures the pre-local-file decisions made by aria2's
/// `RequestGroup::adjustFilename` and `shouldCancelDownloadForSafety`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OutputPathPolicy {
    /// Permit replacing an existing output file from scratch.
    pub allow_overwrite: bool,
    /// Select a numbered output when an existing file cannot be reused.
    pub auto_file_renaming: bool,
    /// Reuse an existing file without a control file when it is no larger
    /// than the known remote file.
    pub continue_download: bool,
    /// Existing data is eligible for a pre-download integrity check.
    pub check_integrity: bool,
    /// Known remote length, when the protocol has already provided it.
    pub total_length: Option<u64>,
}

impl Default for OutputPathPolicy {
    fn default() -> Self {
        Self {
            allow_overwrite: false,
            auto_file_renaming: true,
            continue_download: false,
            check_integrity: false,
            total_length: None,
        }
    }
}

/// Process-wide registry of output paths claimed by active downloads.
///
/// HTTP and Metalink resolve collisions to a distinct filename. BitTorrent
/// reserves its complete file set and rejects an overlap, matching aria2's
/// duplicate-download contract. All paths share the same set so the policies
/// remain effective across protocols.
pub struct ActiveOutputRegistry {
    inner: Arc<Mutex<HashSet<PathBuf>>>,
}

/// Exact output paths owned by one BitTorrent command. Dropping the command
/// releases the complete reservation, including on failed or cancelled runs.
#[cfg(feature = "bittorrent")]
#[must_use = "dropping the reservation releases its output paths"]
pub(crate) struct OutputPathReservation {
    inner: Arc<Mutex<HashSet<PathBuf>>>,
    paths: Vec<PathBuf>,
}

#[cfg(feature = "bittorrent")]
impl Drop for OutputPathReservation {
    fn drop(&mut self) {
        release_paths(&self.inner, &self.paths);
    }
}

impl Default for ActiveOutputRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ActiveOutputRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(HashSet::new())),
        }
    }

    fn lock_paths(&self) -> MutexGuard<'_, HashSet<PathBuf>> {
        self.inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Atomically reserve a set of exact paths for a long-lived command.
    ///
    /// Unlike `resolve_with_policy`, this does not rename colliding paths or
    /// reject paths merely because a file already exists on disk.
    #[cfg(feature = "bittorrent")]
    pub(crate) fn reserve_exact_paths(
        &self,
        paths: impl IntoIterator<Item = PathBuf>,
    ) -> std::result::Result<OutputPathReservation, PathBuf> {
        let paths = paths
            .into_iter()
            .filter(|path| !path.as_os_str().is_empty())
            .collect::<Vec<_>>();

        let mut registry = self.lock_paths();
        if let Some(conflict) = paths.iter().find(|path| registry.contains(*path)) {
            return Err(conflict.clone());
        }
        registry.extend(paths.iter().cloned());

        Ok(OutputPathReservation {
            inner: Arc::clone(&self.inner),
            paths,
        })
    }

    /// Resolve the final output path for a download, registering it to prevent collisions.
    ///
    /// If `desired` is not currently claimed by another active download, it is registered
    /// and returned as-is. If a collision is detected, the method appends `.1`, `.2`,
    /// etc. (before the file extension) until an unused name is found.
    ///
    /// # Returns
    ///
    /// The resolved `PathBuf` that the caller should use for all subsequent disk I/O.
    /// The caller **must** call [`Self::release`] when the download finishes (success or failure).
    pub async fn resolve(&self, desired: &Path) -> PathBuf {
        let mut registry = self.lock_paths();

        if !registry.contains(desired) {
            registry.insert(desired.to_path_buf());
            debug!(
                "Output path registered (no conflict): {}",
                desired.display()
            );
            return desired.to_path_buf();
        }

        // Collision detected — generate unique name with numeric suffix.
        let (stem, ext) = split_filename_for_aria2(desired);

        let parent = desired.parent().unwrap_or_else(|| Path::new("."));

        let mut counter: u32 = 1;
        loop {
            let candidate = parent.join(numbered_filename(&stem, &ext, counter));

            // Check both the in-progress registry AND the filesystem to avoid conflicts
            // with previously completed downloads that happened to use the same suffix.
            if !registry.contains(&candidate) && !candidate.exists() {
                registry.insert(candidate.clone());
                warn!(
                    "Filename collision: '{}' is already in use. Resolved to '{}'",
                    desired.display(),
                    candidate.display()
                );
                return candidate;
            }

            counter += 1;

            // Safety upper bound to prevent unbounded looping in pathological cases.
            if counter > 10_000 {
                let fallback = parent.join(numbered_filename(&stem, "", counter));
                registry.insert(fallback.clone());
                warn!(
                    "Exhausted normal suffix range for '{}', using fallback '{}'",
                    desired.display(),
                    fallback.display()
                );
                return fallback;
            }
        }
    }

    /// Resolve and register an output path using aria2-compatible file policy.
    ///
    /// A control file takes precedence over the existence of the data file.
    /// Without a control file, an existing output is reusable only when
    /// overwrite, integrity checking, or compatible `--continue` semantics
    /// explicitly allow it. Otherwise the original `.N` filename policy is
    /// applied, or `FileAlreadyExists` is returned when auto-renaming is off.
    pub async fn resolve_with_policy(
        &self,
        desired: &Path,
        policy: OutputPathPolicy,
    ) -> Result<PathBuf> {
        let mut registry = self.lock_paths();
        let desired_claimed = registry.contains(desired);
        let desired_exists = desired.exists();
        let desired_has_control = ControlFile::control_path_for(desired).exists();

        let reusable_existing = desired_exists
            && !desired_claimed
            && (policy.allow_overwrite
                || desired_has_control
                || policy.check_integrity
                || (policy.continue_download
                    && compatible_existing_length(desired, policy.total_length)));

        if !desired_claimed && (!desired_exists || reusable_existing) {
            registry.insert(desired.to_path_buf());
            debug!(
                path = %desired.display(),
                reused = desired_exists,
                "Output path registered"
            );
            return Ok(desired.to_path_buf());
        }

        if !policy.auto_file_renaming {
            return Err(Aria2Error::FileAlreadyExists(desired.display().to_string()));
        }

        let (stem, ext) = split_filename_for_aria2(desired);
        let parent = desired.parent().unwrap_or_else(|| Path::new("."));
        for counter in 1..10_000u32 {
            let candidate = parent.join(numbered_filename(&stem, &ext, counter));
            let candidate_has_control = ControlFile::control_path_for(&candidate).exists();
            if !registry.contains(&candidate) && (!candidate.exists() || candidate_has_control) {
                registry.insert(candidate.clone());
                warn!(
                    original = %desired.display(),
                    resolved = %candidate.display(),
                    "Filename collision resolved"
                );
                return Ok(candidate);
            }
        }

        Err(Aria2Error::FileRenamingFailed(
            desired.display().to_string(),
        ))
    }

    /// Release a previously-resolved path from the registry.
    ///
    /// Must be called when a download completes (success or failure) so that the path
    /// becomes available for future downloads if needed.
    pub async fn release(&self, path: &Path) {
        let mut registry = self.lock_paths();
        if registry.remove(path) {
            debug!("Output path released: {}", path.display());
        }
    }

    /// Return the number of paths currently registered (for diagnostics / testing).
    pub async fn len(&self) -> usize {
        self.lock_paths().len()
    }

    /// Check whether the registry is empty.
    pub async fn is_empty(&self) -> bool {
        self.lock_paths().is_empty()
    }
}

#[cfg(feature = "bittorrent")]
fn release_paths(inner: &Mutex<HashSet<PathBuf>>, paths: &[PathBuf]) {
    let mut registry = inner
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    for path in paths {
        registry.remove(path);
    }
}

fn compatible_existing_length(path: &Path, total_length: Option<u64>) -> bool {
    match total_length {
        Some(total_length) => std::fs::metadata(path)
            .map(|metadata| metadata.len() <= total_length)
            .unwrap_or(false),
        // A normal HTTP GET learns the entity length from its response. An
        // explicit --continue still makes an existing local prefix reusable
        // before that response arrives; the Range request validates it.
        None => path.exists(),
    }
}

/// Split a path using the same extension rules as aria2's
/// `RequestGroup::tryAutoFileRenaming`.
fn split_filename_for_aria2(path: &Path) -> (String, String) {
    let file_name = path
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let extension_start = file_name
        .rfind('.')
        .filter(|index| *index > 0 && *index + 1 < file_name.len());
    match extension_start {
        Some(index) => (
            file_name[..index].to_string(),
            file_name[index..].to_string(),
        ),
        None => (file_name, String::new()),
    }
}

/// Build an aria2-style numbered filename without exceeding the portable
/// basename limit. The suffix and extension are retained whenever possible;
/// the stem is shortened first because it carries the least structural value.
fn numbered_filename(stem: &str, ext: &str, counter: u32) -> String {
    let suffix = format!(".{counter}");
    let extension = truncate_utf8(ext, MAX_OUTPUT_FILENAME_BYTES.saturating_sub(suffix.len()));
    let stem_limit = MAX_OUTPUT_FILENAME_BYTES
        .saturating_sub(suffix.len())
        .saturating_sub(extension.len());
    let stem = truncate_utf8(stem, stem_limit);
    format!("{stem}{suffix}{extension}")
}

fn truncate_utf8(value: &str, max_bytes: usize) -> &str {
    let mut end = value.len().min(max_bytes);
    while end > 0 && !value.is_char_boundary(end) {
        end -= 1;
    }
    &value[..end]
}

// ---------------------------------------------------------------------------
// Global singleton — every download command shares the same instance so that
// cross-task collisions are caught regardless of how commands are spawned.
// ---------------------------------------------------------------------------

use std::sync::OnceLock;

/// Global singleton registry instance. Initialized on first access.
static GLOBAL_REGISTRY: OnceLock<ActiveOutputRegistry> = OnceLock::new();

/// Obtain a reference to the global `ActiveOutputRegistry`.
pub fn global_registry() -> &'static ActiveOutputRegistry {
    GLOBAL_REGISTRY.get_or_init(|| {
        info!("Global ActiveOutputRegistry initialized");
        ActiveOutputRegistry::new()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Aria2Error;
    use crate::filesystem::control_file::ControlFile;

    #[tokio::test]
    async fn test_no_collision_when_unique() {
        let reg = ActiveOutputRegistry::new();
        let p1 = reg.resolve(Path::new("/tmp/file.txt")).await;
        assert_eq!(p1, PathBuf::from("/tmp/file.txt"));
        assert_eq!(reg.len().await, 1);
    }

    #[tokio::test]
    async fn test_collision_generates_suffix() {
        let reg = ActiveOutputRegistry::new();

        let p1 = reg.resolve(Path::new("/tmp/file.txt")).await;
        let p2 = reg.resolve(Path::new("/tmp/file.txt")).await;

        assert_eq!(p1, PathBuf::from("/tmp/file.txt"));
        assert_eq!(p2, PathBuf::from("/tmp/file.1.txt"));
        assert_eq!(reg.len().await, 2);
    }

    #[tokio::test]
    async fn test_triple_collision() {
        let reg = ActiveOutputRegistry::new();

        let _p1 = reg.resolve(Path::new("/tmp/data.bin")).await;
        let _p2 = reg.resolve(Path::new("/tmp/data.bin")).await;
        let p3 = reg.resolve(Path::new("/tmp/data.bin")).await;

        assert_eq!(p3, PathBuf::from("/tmp/data.2.bin"));
    }

    #[tokio::test]
    async fn test_release_allows_reuse() {
        let reg = ActiveOutputRegistry::new();

        let p1 = reg.resolve(Path::new("/tmp/reusable.txt")).await;
        reg.release(&p1).await;
        assert!(reg.is_empty().await);

        // After release, the same path can be claimed again.
        let p2 = reg.resolve(Path::new("/tmp/reusable.txt")).await;
        assert_eq!(p2, PathBuf::from("/tmp/reusable.txt"));
    }

    #[tokio::test]
    async fn test_no_extension_handling() {
        let reg = ActiveOutputRegistry::new();

        let p1 = reg.resolve(Path::new("/tmp/Makefile")).await;
        let p2 = reg.resolve(Path::new("/tmp/Makefile")).await;

        assert_eq!(p1, PathBuf::from("/tmp/Makefile"));
        // Files without extension should still get suffixed correctly.
        assert_eq!(p2, PathBuf::from("/tmp/Makefile.1"));
    }

    #[tokio::test]
    async fn test_global_singleton() {
        let r1 = global_registry();
        let r2 = global_registry();
        // Both references must point to the same underlying registry.
        assert!(Arc::ptr_eq(&r1.inner, &r2.inner));
    }

    #[tokio::test]
    async fn existing_file_is_auto_renamed_by_default() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"existing").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(&desired, OutputPathPolicy::default())
            .await
            .unwrap();

        assert_eq!(resolved, dir.path().join("download.1.bin"));
        assert_eq!(tokio::fs::read(&desired).await.unwrap(), b"existing");
    }

    #[tokio::test]
    async fn policy_rename_keeps_extension_and_portable_length_limit() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join(format!("{}{}", "a".repeat(251), ".bin"));
        tokio::fs::write(&desired, b"existing").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(&desired, OutputPathPolicy::default())
            .await
            .unwrap();
        let expected = format!("{}{}", "a".repeat(249), ".1.bin");

        assert_eq!(
            resolved.file_name().unwrap().to_str(),
            Some(expected.as_str())
        );
        assert_eq!(resolved.file_name().unwrap().len(), 255);
    }

    #[tokio::test]
    async fn active_collision_keeps_unextended_name_within_limit() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("a".repeat(255));

        let registry = ActiveOutputRegistry::new();
        let _first = registry.resolve(&desired).await;
        let resolved = registry.resolve(&desired).await;
        let expected = format!("{}{}", "a".repeat(253), ".1");

        assert_eq!(
            resolved.file_name().unwrap().to_str(),
            Some(expected.as_str())
        );
        assert_eq!(resolved.file_name().unwrap().len(), 255);
    }

    #[tokio::test]
    async fn concurrent_policy_reservations_are_unique() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("shared.bin");
        let registry = Arc::new(ActiveOutputRegistry::new());
        let mut tasks = Vec::new();

        for _ in 0..16 {
            let registry = Arc::clone(&registry);
            let desired = desired.clone();
            tasks.push(tokio::spawn(async move {
                registry
                    .resolve_with_policy(&desired, OutputPathPolicy::default())
                    .await
                    .unwrap()
            }));
        }

        let mut resolved = HashSet::new();
        for task in tasks {
            resolved.insert(task.await.unwrap());
        }

        assert_eq!(resolved.len(), 16);
        assert_eq!(registry.len().await, 16);
    }

    #[tokio::test]
    async fn allow_overwrite_keeps_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"existing").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    allow_overwrite: true,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(resolved, desired);
    }

    #[tokio::test]
    async fn continue_keeps_partial_file_when_length_is_compatible() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"partial").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    continue_download: true,
                    total_length: Some(100),
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(resolved, desired);
    }

    #[tokio::test]
    async fn existing_file_without_auto_rename_returns_file_exists() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"existing").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let error = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    auto_file_renaming: false,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .expect_err("existing output must not be silently overwritten");

        assert!(matches!(error, Aria2Error::FileAlreadyExists(_)));
    }

    #[tokio::test]
    async fn existing_control_file_reuses_output_path() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        tokio::fs::write(&desired, b"partial").await.unwrap();
        let control = ControlFile::control_path_for(&desired);
        tokio::fs::write(&control, b"control").await.unwrap();

        let registry = ActiveOutputRegistry::new();
        let resolved = registry
            .resolve_with_policy(&desired, OutputPathPolicy::default())
            .await
            .unwrap();

        assert_eq!(resolved, desired);
    }

    #[tokio::test]
    async fn occupied_output_is_renamed_even_when_overwrite_is_allowed() {
        let dir = tempfile::tempdir().unwrap();
        let desired = dir.path().join("download.bin");
        let registry = ActiveOutputRegistry::new();
        let first = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    allow_overwrite: true,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();
        let second = registry
            .resolve_with_policy(
                &desired,
                OutputPathPolicy {
                    allow_overwrite: true,
                    ..OutputPathPolicy::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(first, desired);
        assert_eq!(second, dir.path().join("download.1.bin"));
    }
}