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
//! Constructors for single-file, multi-file, and grouped Metalink commands.

use std::sync::Arc;
use tracing::info;

use aria2_protocol::metalink::parser::UrlEntry;

use super::{FileDownloadInfo, MetalinkDownloadCommand, MetalinkFileInfo};
use crate::download::{DownloadContext, file_entry::FileEntry};
use crate::error::{Aria2Error, FatalError, Result};
use crate::request::request_group::{DownloadOptions, GroupId, RequestGroup};
use crate::util::rwlock_ext::RwLockRecover;

impl MetalinkDownloadCommand {
    /// Create a `MetalinkDownloadCommand` for a single-file Metalink.
    ///
    /// For multi-file Metalinks, use [`create_multi_file`] instead, which
    /// returns one command per file. This method also works for multi-file
    /// Metalinks: it picks the first file and downloads it.
    ///
    /// # Arguments
    ///
    /// * `gid` - Group ID for the download
    /// * `metalink_bytes` - Raw Metalink XML data
    /// * `options` - Download options
    /// * `output_dir` - Override output directory (takes precedence over `options.dir`)
    pub fn new(
        gid: GroupId,
        metalink_bytes: &[u8],
        options: &DownloadOptions,
        output_dir: Option<&str>,
    ) -> Result<Self> {
        super::validate_http_client_options(options)?;
        let doc = aria2_protocol::metalink::parser::MetalinkDocument::parse(metalink_bytes, None)
            .map_err(|e| {
            Aria2Error::Fatal(FatalError::Config(format!("Metalink parse failed: {}", e)))
        })?;

        if doc.files.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink contains no files".into(),
            )));
        }

        // Use the first file (single-file mode). For multi-file Metalinks,
        // the caller should use create_multi_file() instead.
        let file = &doc.files[0];

        if file.urls.is_empty() {
            // A torrent metaurl is still a valid download path (C++
            // BtDependency); reject only when there is nothing at all.
            let has_torrent_metaurl = file
                .meta_urls
                .iter()
                .any(|m| m.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent);
            if !has_torrent_metaurl {
                return Err(Aria2Error::Fatal(FatalError::Config(
                    "Metalink file has no download URL".into(),
                )));
            }
        }

        let dir = output_dir
            .map(|d| d.to_string())
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());

        let filename = file.name.clone();
        let path = std::path::PathBuf::from(&dir).join(&filename);

        let urls: Vec<String> = file
            .get_sorted_urls()
            .iter()
            .map(|u| u.url.clone())
            .collect();
        let file_info = FileDownloadInfo {
            expected_size: file.size,
            hash_entry: file.strongest_hash().cloned(),
            sorted_urls: file.get_sorted_urls().into_iter().cloned().collect(),
            pieces: file.pieces.clone(),
            torrent_metaurls: file
                .meta_urls
                .iter()
                .filter(|metaurl| {
                    metaurl.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent
                })
                .cloned()
                .collect(),
        };
        let group = RequestGroup::new(gid, urls, options.clone());
        group.set_output_name(file.name.clone());

        if doc.files.len() > 1 {
            info!(
                "MetalinkDownloadCommand created for first file of {}: {} -> {} ({} mirrors) \
                 [use create_multi_file() for all files]",
                doc.files.len(),
                file.name,
                path.display(),
                file.urls.len()
            );
        } else {
            info!(
                "MetalinkDownloadCommand created: {} -> {} ({} mirrors)",
                file.name,
                path.display(),
                file.urls.len()
            );
        }

        Ok(Self {
            group: Arc::new(std::sync::RwLock::new(group)),
            output_path: path,
            started: false,
            completed: false,
            completed_bytes: 0,
            progress_offset: 0,
            file_info: Some(file_info),
            grouped_file_infos: Vec::new(),
            protocol_runtime: None,
            global_limiter: None,
            outbound_network_policy: Arc::new(crate::network::OutboundNetworkPolicy::direct()),
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: None,
            #[cfg(feature = "bittorrent")]
            bt_registry: None,
            #[cfg(feature = "bittorrent")]
            bt_listener: None,
            #[cfg(feature = "bittorrent")]
            lpd_manager: None,
            #[cfg(feature = "bittorrent")]
            open_file_budget: None,
        })
    }

    /// Create one `MetalinkDownloadCommand` per file in a multi-file Metalink.
    ///
    /// This is the Rust equivalent of C++ `Metalink2RequestGroup::createRequestGroup()`
    /// which creates one `RequestGroup` per `MetalinkEntry`. Each command
    /// downloads exactly one file from the Metalink using its own mirror list.
    /// Torrent metaurls are retained in `FileDownloadInfo` for the execution
    /// fallback when no direct mirror succeeds.
    ///
    /// # Arguments
    ///
    /// * `metalink_bytes` - Raw Metalink XML data
    /// * `options` - Download options (shared by all files)
    /// * `output_dir` - Override output directory
    /// * `gid_start` - Starting GID; each file gets `gid_start + i`
    ///
    /// # Returns
    ///
    /// A vector of `MetalinkFileInfo`, one per file with HTTP/FTP resources or
    /// a BitTorrent metaurl. Files with no supported resource are skipped.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let commands = MetalinkDownloadCommand::create_multi_file(
    ///     &metalink_xml, &options, None, None, 100
    /// )?;
    /// for info in commands {
    ///     println!("File {}: {}", info.file_index, info.command.output_path.display());
    /// }
    /// ```
    /// Create per-file commands while resolving relative Metalink URLs
    /// against the source document URI.
    pub fn create_multi_file(
        metalink_bytes: &[u8],
        options: &DownloadOptions,
        output_dir: Option<&str>,
        base_uri: Option<&str>,
        gid_start: u64,
    ) -> Result<Vec<MetalinkFileInfo>> {
        super::validate_http_client_options(options)?;
        let doc =
            aria2_protocol::metalink::parser::MetalinkDocument::parse(metalink_bytes, base_uri)
                .map_err(|e| {
                    Aria2Error::Fatal(FatalError::Config(format!("Metalink parse failed: {}", e)))
                })?;

        if doc.files.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink contains no files".into(),
            )));
        }

        let dir = output_dir
            .map(|d| d.to_string())
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());

        let mut commands = Vec::with_capacity(doc.files.len());

        for (i, file) in doc.files.iter().enumerate() {
            let has_torrent_metaurl = file.meta_urls.iter().any(|metaurl| {
                metaurl.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent
            });
            if file.urls.is_empty() && !has_torrent_metaurl {
                tracing::debug!(
                    index = i,
                    name = %file.name,
                    "Skipping Metalink file with no downloadable resources"
                );
                continue;
            }

            let gid = GroupId::new(gid_start + i as u64);
            let path = std::path::PathBuf::from(&dir).join(&file.name);

            let sorted_urls: Vec<UrlEntry> = file
                .get_sorted_urls()
                .iter()
                .map(|u| (*u).clone())
                .collect();
            let urls: Vec<String> = sorted_urls
                .iter()
                .filter(|u| u.is_non_p2p())
                .map(|u| u.url.clone())
                .collect();
            let group = RequestGroup::new(gid, urls, options.clone());
            group.set_output_name(file.name.clone());

            let file_info = FileDownloadInfo {
                expected_size: file.size,
                hash_entry: file.strongest_hash().cloned(),
                sorted_urls,
                pieces: file.pieces.clone(),
                torrent_metaurls: file
                    .meta_urls
                    .iter()
                    .filter(|m| m.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent)
                    .cloned()
                    .collect(),
            };

            info!(
                gid = gid.value(),
                index = i,
                name = %file.name,
                path = %path.display(),
                mirrors = file.urls.len(),
                "Created MetalinkDownloadCommand for file"
            );

            commands.push(MetalinkFileInfo {
                command: Self {
                    group: Arc::new(std::sync::RwLock::new(group)),
                    output_path: path,
                    started: false,
                    completed: false,
                    completed_bytes: 0,
                    progress_offset: 0,
                    file_info: Some(file_info),
                    grouped_file_infos: Vec::new(),
                    protocol_runtime: None,
                    global_limiter: None,
                    outbound_network_policy: Arc::new(
                        crate::network::OutboundNetworkPolicy::direct(),
                    ),
                    #[cfg(feature = "bittorrent")]
                    public_tracker_catalog: None,
                    #[cfg(feature = "bittorrent")]
                    bt_registry: None,
                    #[cfg(feature = "bittorrent")]
                    bt_listener: None,
                    #[cfg(feature = "bittorrent")]
                    lpd_manager: None,
                    #[cfg(feature = "bittorrent")]
                    open_file_budget: None,
                },
                file_index: i,
            });
        }

        Ok(commands)
    }

    /// Create a `MetalinkDownloadCommand` from a pre-parsed, pre-sorted
    /// `MetalinkFile` entry.
    ///
    /// This is used by `MetalinkToRequestGroup` which handles its own
    /// parsing, filtering, and priority reordering. Unlike `create_multi_file`,
    /// this method does not re-parse the XML.
    ///
    /// # Arguments
    ///
    /// * `file` - Pre-parsed Metalink file entry with sorted URLs
    /// * `options` - Download options
    /// * `output_dir` - Override output directory
    /// * `gid_start` - Starting GID for this command
    pub fn create_multi_file_for_single(
        file: &aria2_protocol::metalink::parser::MetalinkFile,
        options: &DownloadOptions,
        output_dir: Option<&str>,
        gid_start: u64,
    ) -> Result<Vec<MetalinkFileInfo>> {
        super::validate_http_client_options(options)?;
        let dir = output_dir
            .map(|d| d.to_string())
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());

        let torrent_metaurls: Vec<_> = file
            .meta_urls
            .iter()
            .filter(|metaurl| {
                metaurl.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent
            })
            .cloned()
            .collect();
        if file.urls.is_empty() && torrent_metaurls.is_empty() {
            return Ok(Vec::new());
        }

        let gid = GroupId::new(gid_start);
        let path = std::path::PathBuf::from(&dir).join(&file.name);

        let sorted_urls: Vec<UrlEntry> = file
            .get_sorted_urls()
            .iter()
            .map(|u| (*u).clone())
            .collect();

        // Collect only non-P2P URLs (HTTP, HTTPS, FTP) for the URI list.
        // BitTorrent URLs go through a separate dependency mechanism.
        // Mirrors C++ AccumulateNonP2PUri.
        let urls: Vec<String> = sorted_urls
            .iter()
            .filter(|u| u.is_non_p2p())
            .map(|u| u.url.clone())
            .collect();

        if urls.is_empty() && torrent_metaurls.is_empty() {
            tracing::debug!(
                name = %file.name,
                "Skipping Metalink file with no downloadable resources"
            );
            return Ok(Vec::new());
        }

        let group = RequestGroup::new(gid, urls, options.clone());
        group.set_output_name(file.name.clone());

        let file_info = FileDownloadInfo {
            expected_size: file.size,
            hash_entry: file.strongest_hash().cloned(),
            sorted_urls,
            pieces: file.pieces.clone(),
            torrent_metaurls,
        };

        info!(
            gid = gid.value(),
            name = %file.name,
            path = %path.display(),
            mirrors = file.urls.len(),
            "Created MetalinkDownloadCommand for single file"
        );

        Ok(vec![MetalinkFileInfo {
            command: Self {
                group: Arc::new(std::sync::RwLock::new(group)),
                output_path: path,
                started: false,
                completed: false,
                completed_bytes: 0,
                progress_offset: 0,
                file_info: Some(file_info),
                grouped_file_infos: Vec::new(),
                protocol_runtime: None,
                global_limiter: None,
                outbound_network_policy: Arc::new(crate::network::OutboundNetworkPolicy::direct()),
                #[cfg(feature = "bittorrent")]
                public_tracker_catalog: None,
                #[cfg(feature = "bittorrent")]
                bt_registry: None,
                #[cfg(feature = "bittorrent")]
                bt_listener: None,
                #[cfg(feature = "bittorrent")]
                lpd_manager: None,
                #[cfg(feature = "bittorrent")]
                open_file_budget: None,
            },
            file_index: 0,
        }])
    }

    /// Create one command for a Metalink metaurl group.
    ///
    /// The request context contains one `FileEntry` per selected Metalink
    /// file. This preserves aria2's multi-file group semantics while keeping
    /// execution in the Rust command model instead of duplicating a command
    /// per file.
    pub(crate) fn create_multi_file_group(
        files: &[aria2_protocol::metalink::parser::MetalinkFile],
        options: &DownloadOptions,
        output_dir: Option<&str>,
        gid: u64,
    ) -> Result<Self> {
        super::validate_http_client_options(options)?;
        if files.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink group contains no files".to_string(),
            )));
        }

        let dir = output_dir
            .map(str::to_owned)
            .or_else(|| options.dir.clone())
            .unwrap_or_else(|| ".".to_string());
        let mut entries = Vec::with_capacity(files.len());
        let mut grouped_file_infos = Vec::with_capacity(files.len());
        let mut offset = 0u64;

        for file in files {
            let sorted_urls: Vec<UrlEntry> = file.get_sorted_urls().into_iter().cloned().collect();
            let urls: Vec<String> = sorted_urls
                .iter()
                .filter(|url| url.is_non_p2p())
                .map(|url| url.url.clone())
                .collect();
            let torrent_metaurls = file
                .meta_urls
                .iter()
                .filter(|metaurl| {
                    metaurl.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent
                })
                .cloned()
                .collect::<Vec<_>>();
            if urls.is_empty() && torrent_metaurls.is_empty() {
                continue;
            }

            let path = std::path::PathBuf::from(&dir).join(&file.name);
            let mut entry = FileEntry::new(
                path.to_string_lossy().into_owned(),
                file.size.unwrap_or(0),
                offset,
                urls.clone(),
            );
            if let Some(original_name) = torrent_metaurls
                .first()
                .and_then(|metaurl| metaurl.name.clone())
            {
                entry.set_original_name(original_name);
            }
            entry.set_suffix_path(file.name.clone());
            entry.set_max_connection_per_server(
                options
                    .max_connection_per_server
                    .unwrap_or(crate::constants::DEFAULT_MAX_CONNECTION_PER_SERVER as u16)
                    .clamp(1, 16) as usize,
            );
            entry.set_unique_protocol(options.metalink_enable_unique_protocol);
            offset = offset.saturating_add(file.size.unwrap_or(0));
            entries.push(entry);
            grouped_file_infos.push((
                path,
                FileDownloadInfo {
                    expected_size: file.size,
                    hash_entry: file.strongest_hash().cloned(),
                    sorted_urls,
                    pieces: file.pieces.clone(),
                    torrent_metaurls,
                },
            ));
        }

        if grouped_file_infos.is_empty() {
            return Err(Aria2Error::Fatal(FatalError::Config(
                "Metalink group contains no downloadable files".to_string(),
            )));
        }

        let group = RequestGroup::new(GroupId::new(gid), Vec::new(), options.clone());
        let mut context = DownloadContext::new_default();
        context.set_file_entries(entries);
        group.set_download_context(Arc::new(context));
        group.set_output_name(files[0].name.clone());
        let output_path = grouped_file_infos[0].0.clone();

        Ok(Self {
            group: Arc::new(std::sync::RwLock::new(group)),
            output_path,
            started: false,
            completed: false,
            completed_bytes: 0,
            progress_offset: 0,
            file_info: None,
            grouped_file_infos,
            protocol_runtime: None,
            global_limiter: None,
            outbound_network_policy: Arc::new(crate::network::OutboundNetworkPolicy::direct()),
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: None,
            #[cfg(feature = "bittorrent")]
            bt_registry: None,
            #[cfg(feature = "bittorrent")]
            bt_listener: None,
            #[cfg(feature = "bittorrent")]
            lpd_manager: None,
            #[cfg(feature = "bittorrent")]
            open_file_budget: None,
        })
    }

    /// Create a manager-owned Metalink command for one parsed file entry.
    #[cfg(feature = "metalink")]
    pub(crate) fn new_with_group_source(
        group: Arc<std::sync::RwLock<RequestGroup>>,
        metalink_bytes: &[u8],
        file_index: usize,
        options: &DownloadOptions,
        base_uri: Option<&str>,
        policy: &crate::network::OutboundNetworkPolicy,
    ) -> Result<Self> {
        let doc =
            aria2_protocol::metalink::parser::MetalinkDocument::parse(metalink_bytes, base_uri)
                .map_err(|e| {
                    Aria2Error::Fatal(FatalError::Config(format!("Metalink parse failed: {e}")))
                })?;
        let mut file = doc.files.get(file_index).cloned().ok_or_else(|| {
            Aria2Error::Fatal(FatalError::Config(
                "Metalink file index out of range".to_string(),
            ))
        })?;
        // The manager stores raw Metalink bytes so the task can be rebuilt
        // after a restart. Reapply the same resource normalization used when
        // the group was created; otherwise location/protocol preferences are
        // silently lost at execution time.
        crate::engine::metalink::to_request_group::MetalinkToRequestGroup::new()
            .normalize_file_for_runtime(&mut file, options);
        Self::new_with_group_file(group, &file, options, policy)
    }

    /// Create a manager-owned command from a file parsed during initial
    /// Metalink expansion. The file is already normalized by the shared
    /// selection pass; restored groups use `new_with_group_source` instead.
    #[cfg(feature = "metalink")]
    pub(crate) fn new_with_group_file(
        group: Arc<std::sync::RwLock<RequestGroup>>,
        file: &aria2_protocol::metalink::parser::MetalinkFile,
        options: &DownloadOptions,
        policy: &crate::network::OutboundNetworkPolicy,
    ) -> Result<Self> {
        super::validate_http_client_options(options)?;
        let dir = options.dir.as_deref().unwrap_or(".");
        let output_name = group
            .recover()
            .output_name()
            .unwrap_or_else(|| file.name.clone());
        let path = std::path::PathBuf::from(dir).join(output_name);
        let sorted_urls: Vec<UrlEntry> = file.get_sorted_urls().into_iter().cloned().collect();
        let file_info = FileDownloadInfo {
            expected_size: file.size,
            hash_entry: file.strongest_hash().cloned(),
            pieces: file.pieces.clone(),
            torrent_metaurls: file
                .meta_urls
                .iter()
                .filter(|m| m.mediatype == aria2_protocol::metalink::parser::MediaType::Torrent)
                .cloned()
                .collect(),
            sorted_urls,
        };
        Ok(Self {
            group,
            output_path: path,
            started: false,
            completed: false,
            completed_bytes: 0,
            progress_offset: 0,
            file_info: Some(file_info),
            grouped_file_infos: Vec::new(),
            protocol_runtime: None,
            global_limiter: None,
            outbound_network_policy: Arc::new(policy.clone()),
            #[cfg(feature = "bittorrent")]
            public_tracker_catalog: None,
            #[cfg(feature = "bittorrent")]
            bt_registry: None,
            #[cfg(feature = "bittorrent")]
            bt_listener: None,
            #[cfg(feature = "bittorrent")]
            lpd_manager: None,
            #[cfg(feature = "bittorrent")]
            open_file_budget: None,
        })
    }
}