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
//! Resolve a safe local filename from an HTTP response and its effective URL.
//!
//! The module owns one small interface for the policy: an unambiguous
//! Content-Disposition value wins, then the final URL path segment, then the
//! aria2 compatibility fallback. HTTP parsing and local filename
//! normalization remain separate so the safety policy is applied uniformly.

use tracing::debug;

use crate::http::content_disposition::parse_content_disposition_with_default_utf8;
use crate::http::header_processor::HttpResponseHead;

/// Determine the output filename from response metadata or the effective URL.
///
/// A caller that already has an explicit output path must bypass this
/// function. The returned value is always a safe basename.
///
/// # Arguments
///
/// * `response_head` - Parsed HTTP response headers.
/// * `request_url` - The URL associated with this response. After a redirect,
///   callers should pass the final response URL.
/// * `content_disposition_default_utf8` - Whether to treat Content-Disposition
///   filename as UTF-8 by default (maps to C++ `PREF_CONTENT_DISPOSITION_DEFAULT_UTF8`).
///
/// # Returns
///
/// The determined filename (basename only, no directory prefix).
pub fn determine_filename(
    response_head: &HttpResponseHead,
    request_url: &str,
    content_disposition_default_utf8: bool,
) -> String {
    if let Some(filename) =
        content_disposition_filename(response_head, content_disposition_default_utf8)
    {
        debug!(
            filename = %filename,
            source = "Content-Disposition",
            "Filename determined"
        );
        return filename;
    }

    let filename = crate::validation::uri::sanitize_filename_from_uri(request_url);
    debug!(filename = %filename, source = "URL", "Filename determined");
    filename
}

/// Determine a filename directly from a reqwest response.
///
/// This is the reqwest response entry point used by the download engine.
/// Keeping the conversion here prevents the reqwest path from growing a
/// second Content-Disposition parser or a second URL sanitization policy.
pub(crate) fn determine_filename_from_response(
    response: &reqwest::Response,
    content_disposition_default_utf8: bool,
) -> String {
    let headers = response
        .headers()
        .iter()
        .filter_map(|(name, value)| {
            Some((
                name.as_str().to_ascii_lowercase(),
                value.to_str().ok()?.to_owned(),
            ))
        })
        .collect();
    let head = HttpResponseHead::new(
        format!("{:?}", response.version()),
        response.status().as_u16(),
        response
            .status()
            .canonical_reason()
            .unwrap_or_default()
            .to_owned(),
        headers,
    );
    determine_filename(
        &head,
        response.url().as_str(),
        content_disposition_default_utf8,
    )
}

/// Return the only usable Content-Disposition value.
///
/// Multiple values are ambiguous and are ignored as a group. This makes the
/// result independent of header ordering and intermediary behaviour.
fn content_disposition_filename(
    response_head: &HttpResponseHead,
    default_utf8: bool,
) -> Option<String> {
    let values = response_head.header_all("content-disposition");
    let value = match values.as_slice() {
        [] => return None,
        [value] => value,
        _ => {
            debug!(
                count = values.len(),
                "Ignoring duplicate Content-Disposition headers"
            );
            return None;
        }
    };

    let candidate = parse_content_disposition_filename(value, default_utf8)?;
    crate::validation::uri::sanitize_filename_candidate(&candidate)
}

/// Parse filename from Content-Disposition header value using the full
/// RFC 6266 state-machine parser.
///
/// This delegates to `content_disposition::parse_content_disposition_with_default_utf8()` which
/// handles:
/// - `filename*` (RFC 5987 extended form: `charset'language'percent-encoded-value`)
/// - `filename` (quoted with backslash escaping, or unquoted token)
/// - Duplicate parameter rejection (C++ returns -1 for duplicates)
/// - `defaultUTF8` mode: validates quoted-string bytes as UTF-8 or ISO-8859-1
/// - Directory-traversal detection (`detectDirTraversal`)
/// - ISO-8859-1 → UTF-8 conversion
///
/// Additionally, we reject filenames containing `/` or `\` anywhere, matching
/// the C++ `getContentDispositionFilename()` check:
/// `res.find_first_of("/\\") == std::string::npos`.
///
/// Returns `None` if no valid filename is found or the filename is rejected.
fn parse_content_disposition_filename(cd_value: &str, default_utf8: bool) -> Option<String> {
    let result = parse_content_disposition_with_default_utf8(cd_value, default_utf8);

    // If parsing failed (disposition_type is empty), no valid filename
    if result.disposition_type.is_empty() {
        return None;
    }

    // Get the filename (prefers filename* over filename= per RFC 6266)
    let filename = result.filename?;

    // Additional C++ check: reject filenames containing '/' or '\'.
    // C++ getContentDispositionFilename() does:
    //   if (!detectDirTraversal(res) &&
    //       res.find_first_of("/\\") == std::string::npos) { return res; }
    // The content_disposition parser's is_dir_traversal already handles
    // most cases (starting /, containing \, etc.), but does NOT reject
    // plain "subdir/file.txt" (multi-segment path without traversal).
    // The C++ find_first_of check catches these cases.
    if filename.contains('/') || filename.contains('\\') {
        debug!(
            filename = %filename,
            "Content-Disposition filename rejected: contains path separator"
        );
        return None;
    }

    Some(filename)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::header_processor::HttpHeaderProcessor;
    use crate::validation::uri::sanitize_filename_candidate as sanitize_filename;

    /// Helper: parse raw HTTP response bytes into HttpResponseHead.
    fn parse_head(raw: &[u8]) -> HttpResponseHead {
        let mut proc = HttpHeaderProcessor::new();
        proc.feed(raw);
        proc.get_result().unwrap()
    }

    // ── URL filename tests ──────────────────────────────────────────────

    #[test]
    fn test_filename_from_url_path() {
        let head = parse_head(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(&head, "http://example.com/path/to/file.txt", false);
        assert_eq!(filename, "file.txt");
    }

    #[test]
    fn test_filename_from_url_trailing_slash() {
        let head = parse_head(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(&head, "http://example.com/dir/", false);
        assert_eq!(filename, "index.html");
    }

    #[test]
    fn test_filename_from_url_percent_encoded() {
        let head = parse_head(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(&head, "http://example.com/path/my%20file.txt", false);
        assert_eq!(filename, "my file.txt");
    }

    #[test]
    fn test_filename_from_url_utf8_percent_encoded() {
        // CJK characters in URL: 日本語 = %E6%97%A5%E6%9C%AC%E8%AA%9E
        let head = parse_head(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(
            &head,
            "http://example.com/%E6%97%A5%E6%9C%AC%E8%AA%9E.txt",
            false,
        );
        assert_eq!(filename, "\u{65e5}\u{672c}\u{8a9e}.txt");
    }

    #[test]
    fn test_filename_from_url_decodes_only_after_extracting_segment() {
        let head = parse_head(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(
            &head,
            "https://example.com/archive/dir%2Freport.txt?token=ignored#fragment",
            false,
        );
        assert_eq!(filename, "report.txt");
    }

    #[test]
    fn test_filename_from_url_preserves_invalid_utf8_as_replacement() {
        let head = parse_head(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(&head, "https://example.com/%FF.bin", false);
        assert_eq!(filename, "\u{fffd}.bin");
    }

    // ── Content-Disposition filename tests ──────────────────────────────

    #[test]
    fn test_filename_from_content_disposition_quoted() {
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=\"my file.pdf\"\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/download", false);
        assert_eq!(filename, "my file.pdf");
    }

    #[test]
    fn test_filename_from_content_disposition_unquoted() {
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=report.csv\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/download", false);
        assert_eq!(filename, "report.csv");
    }

    #[test]
    fn test_filename_from_content_disposition_star() {
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename*=UTF-8''my%20doc.txt\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/download", false);
        assert_eq!(filename, "my doc.txt");
    }

    #[test]
    fn test_filename_content_disposition_priority_over_url() {
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: inline; filename=\"override.txt\"\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/original.txt", false);
        assert_eq!(filename, "override.txt");
    }

    #[test]
    fn test_filename_star_priority_over_filename() {
        // RFC 6266: filename* takes priority over filename
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=\"fallback.txt\"; filename*=UTF-8''preferred.txt\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/download", false);
        assert_eq!(filename, "preferred.txt");
    }

    #[test]
    fn test_filename_star_with_cjk() {
        // Japanese: こんにちは = %e3%81%93%e3%82%93%e3%81%ab%e3%81%a1%e3%81%af
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename*=UTF-8''%e3%81%93%e3%82%93%e3%81%ab%e3%81%a1%e3%81%af.txt\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/download", false);
        assert_eq!(filename, "\u{3053}\u{3093}\u{306b}\u{3061}\u{306f}.txt");
    }

    // ── Path separator rejection (C++ getContentDispositionFilename) ────

    #[test]
    fn test_content_disposition_path_separator_rejected() {
        // C++ rejects filenames with '/' in getContentDispositionFilename
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=\"subdir/file.txt\"\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/original.txt", false);
        // Should fall back to URL filename since Content-Disposition has path separator
        assert_eq!(filename, "original.txt");
    }

    #[test]
    fn test_content_disposition_backslash_rejected() {
        // C++ rejects filenames with '\' in getContentDispositionFilename
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=\"dir\\\\file.txt\"\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/original.txt", false);
        // Should fall back to URL filename
        assert_eq!(filename, "original.txt");
    }

    #[test]
    fn test_content_disposition_directory_traversal_rejected() {
        // Directory traversal patterns should be rejected
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=\"../etc/passwd\"\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/original.txt", false);
        assert_eq!(filename, "original.txt");
    }

    // ── Duplicate parameter rejection (C++ parse_content_disposition) ──

    #[test]
    fn test_duplicate_filename_rejected() {
        // C++ returns -1 for duplicate filename= parameters
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=first.txt; filename=second.txt\r\n\r\n",
        );
        let filename = determine_filename(&head, "http://example.com/original.txt", false);
        // Parse failure → fall back to URL
        assert_eq!(filename, "original.txt");
    }

    // ── filename normalization tests ────────────────────────────────────

    #[test]
    fn test_sanitize_filename() {
        assert_eq!(
            sanitize_filename("normal.txt"),
            Some("normal.txt".to_string())
        );
        assert_eq!(
            sanitize_filename("path/to/file.txt"),
            Some("file.txt".to_string())
        );
        assert_eq!(sanitize_filename("win\\path"), Some("path".to_string()));
        assert_eq!(
            sanitize_filename("null\0byte"),
            Some("nullbyte".to_string())
        );
        assert_eq!(sanitize_filename("CON.txt"), Some("_CON.txt".to_string()));
        assert_eq!(sanitize_filename("CON "), Some("_CON".to_string()));
        assert_eq!(sanitize_filename("COM1."), Some("_COM1".to_string()));
        assert_eq!(sanitize_filename(".."), None);
    }

    #[test]
    fn test_sanitize_filename_handles_reserved_names_and_utf8_length() {
        for (input, expected) in [
            ("PRN.txt", "_PRN.txt"),
            ("AUX", "_AUX"),
            ("NUL.log", "_NUL.log"),
            ("LPT9.csv", "_LPT9.csv"),
            ("COM0.txt", "COM0.txt"),
        ] {
            assert_eq!(sanitize_filename(input), Some(expected.to_owned()));
        }

        let filename = sanitize_filename(&"界".repeat(100)).unwrap();
        assert_eq!(filename, "界".repeat(85));
        assert_eq!(filename.len(), 255);
    }

    #[test]
    fn test_content_disposition_default_utf8_is_honored() {
        let head = parse_head(
            "HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=\"café.txt\"\r\n\r\n"
                .as_bytes(),
        );

        assert_eq!(
            determine_filename(&head, "https://example.com/fallback.txt", true),
            "café.txt"
        );
        assert_eq!(
            determine_filename(&head, "https://example.com/fallback.txt", false),
            "café.txt"
        );
    }

    #[test]
    fn test_duplicate_content_disposition_headers_fall_back_to_url() {
        let head = parse_head(
            b"HTTP/1.1 200 OK\r\nContent-Disposition: attachment; filename=first.txt\r\nContent-Disposition: attachment; filename=second.txt\r\n\r\n",
        );
        assert_eq!(
            determine_filename(&head, "https://example.com/fallback.txt", false),
            "fallback.txt"
        );
    }

    // ── No Content-Disposition falls back to URL ────────────────────────

    #[test]
    fn test_no_content_disposition_uses_url() {
        let head = parse_head(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(&head, "http://example.com/data.csv", false);
        assert_eq!(filename, "data.csv");
    }

    #[test]
    fn test_empty_content_disposition_uses_url() {
        let head =
            parse_head(b"HTTP/1.1 200 OK\r\nContent-Disposition: \r\nContent-Length: 100\r\n\r\n");
        let filename = determine_filename(&head, "http://example.com/data.csv", false);
        assert_eq!(filename, "data.csv");
    }
}