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
use super::*;

#[tokio::test]
async fn resumed_download_reuses_content_disposition_path_with_control_file() {
    use crate::filesystem::control_file::ControlFile;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind resume filename fixture");
    let address = listener
        .local_addr()
        .expect("read resume filename fixture address");
    let server = tokio::spawn(async move {
        for request_index in 0..2 {
            let (mut stream, _) = listener
                .accept()
                .await
                .expect("accept resume filename request");
            let mut request = [0u8; 4096];
            let bytes = stream
                .read(&mut request)
                .await
                .expect("read resume filename request");
            let request = String::from_utf8_lossy(&request[..bytes]);
            let request_lower = request.to_ascii_lowercase();
            if request_index == 0 {
                assert!(!request_lower.contains("range: bytes="));
                stream
                    .write_all(
                        b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nAccept-Ranges: bytes\r\nContent-Disposition: attachment; filename=actual.txt\r\nConnection: close\r\n\r\nabcd",
                    )
                    .await
                    .expect("write resume metadata response");
            } else {
                assert!(request_lower.contains("range: bytes=2-"));
                stream
                    .write_all(
                        b"HTTP/1.1 206 Partial Content\r\nContent-Length: 2\r\nContent-Range: bytes 2-3/4\r\nContent-Disposition: attachment; filename=actual.txt\r\nConnection: close\r\n\r\ncd",
                    )
                    .await
                    .expect("write resume range response");
            }
        }
    });

    let directory = tempfile::tempdir().expect("create resume output directory");
    let output = directory.path().join("actual.txt");
    tokio::fs::write(&output, b"ab")
        .await
        .expect("create partial output");
    let control_path = ControlFile::control_path_for(&output);
    let mut control = ControlFile::open_or_create(&control_path, 4, 1)
        .await
        .expect("create resume control file");
    control.update_completed_length(2);
    control.save().await.expect("save resume control file");

    let options = DownloadOptions {
        dir: Some(directory.path().to_string_lossy().into_owned()),
        continue_download: true,
        force_sequential: true,
        ..DownloadOptions::default()
    };
    let uri = format!("http://{address}/download");
    let mut command = DownloadCommand::new(GroupId::new(1007), &uri, &options, None, None)
        .expect("create resume filename command");

    tokio::time::timeout(Duration::from_secs(5), command.execute())
        .await
        .expect("resume filename download should not hang")
        .expect("resume filename download should complete");

    assert_eq!(tokio::fs::read(&output).await.unwrap(), b"abcd");
    assert!(!directory.path().join("actual.1.txt").exists());
    server.await.expect("resume filename fixture should finish");
}

#[tokio::test]
async fn mirror_resume_failure_reuses_resolved_output_path() {
    use crate::filesystem::control_file::ControlFile;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let first_listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind first mirror fixture");
    let first_address = first_listener
        .local_addr()
        .expect("read first mirror fixture address");
    let first_server = tokio::spawn(async move {
        for request_index in 0..2 {
            let (mut stream, _) = first_listener
                .accept()
                .await
                .expect("accept first mirror request");
            let mut request = [0u8; 4096];
            let bytes = stream
                .read(&mut request)
                .await
                .expect("read first mirror request");
            let request = String::from_utf8_lossy(&request[..bytes]);
            let request_lower = request.to_ascii_lowercase();

            if request_index == 0 {
                assert!(request.starts_with("GET /download.bin HTTP/1.1\r\n"));
                assert!(!request_lower.contains("range: bytes="));
            } else {
                assert!(request.starts_with("GET /download.bin HTTP/1.1\r\n"));
                assert!(request_lower.contains("range: bytes=2-"));
            }

            stream
                .write_all(
                    b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nContent-Disposition: attachment; filename=first.txt\r\nConnection: close\r\n\r\nabcd",
                )
                .await
                .expect("write first mirror response");
        }
    });

    let second_listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind second mirror fixture");
    let second_address = second_listener
        .local_addr()
        .expect("read second mirror fixture address");
    let second_server = tokio::spawn(async move {
        let (mut stream, _) = second_listener
            .accept()
            .await
            .expect("accept second mirror request");
        let mut request = [0u8; 4096];
        let bytes = stream
            .read(&mut request)
            .await
            .expect("read second mirror request");
        let request = String::from_utf8_lossy(&request[..bytes]);
        let request_lower = request.to_ascii_lowercase();
        assert!(request.starts_with("GET /download.bin HTTP/1.1\r\n"));
        assert!(request_lower.contains("range: bytes=2-"));
        stream
            .write_all(
                b"HTTP/1.1 206 Partial Content\r\nContent-Length: 2\r\nContent-Range: bytes 2-3/4\r\nContent-Disposition: attachment; filename=second.txt\r\nConnection: close\r\n\r\ncd",
            )
            .await
            .expect("write second mirror response");
    });

    let directory = tempfile::tempdir().expect("create mirror resume output directory");
    let output = directory.path().join("first.txt");
    tokio::fs::write(&output, b"ab")
        .await
        .expect("create mirror resume partial output");
    let control_path = ControlFile::control_path_for(&output);
    let mut control = ControlFile::open_or_create(&control_path, 4, 1)
        .await
        .expect("create mirror resume control file");
    control.update_completed_length(2);
    control
        .save()
        .await
        .expect("save mirror resume control file");

    let first_uri = format!("http://{first_address}/download.bin");
    let second_uri = format!("http://{second_address}/download.bin");
    let options = DownloadOptions {
        dir: Some(directory.path().to_string_lossy().into_owned()),
        continue_download: true,
        force_sequential: true,
        ..DownloadOptions::default()
    };
    let group = std::sync::Arc::new(std::sync::RwLock::new(RequestGroup::new(
        GroupId::new(1010),
        vec![first_uri.clone(), second_uri],
        options.clone(),
    )));
    let mut command = DownloadCommand::new_with_group(group, &first_uri, &options, None, None)
        .expect("create mirror resume command");

    tokio::time::timeout(Duration::from_secs(5), command.execute())
        .await
        .expect("mirror resume download should not hang")
        .expect("mirror resume download should complete");

    assert_eq!(tokio::fs::read(&output).await.unwrap(), b"abcd");
    assert!(!directory.path().join("first.1.txt").exists());
    assert!(!directory.path().join("second.txt").exists());
    first_server
        .await
        .expect("first mirror fixture should finish");
    second_server
        .await
        .expect("second mirror fixture should finish");
}

#[tokio::test]
async fn cannot_resume_falls_back_to_fresh_download_without_renaming_path() {
    use crate::filesystem::control_file::ControlFile;
    use tokio::io::AsyncWriteExt;
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind cannot-resume filename fixture");
    let address = listener
        .local_addr()
        .expect("read cannot-resume filename fixture address");
    let server = tokio::spawn(async move {
        for request_index in 0..4 {
            let (mut stream, _) = listener
                .accept()
                .await
                .expect("accept cannot-resume filename request");
            let request = read_http_request(&mut stream).await;
            let request_lower = request.to_ascii_lowercase();
            match request_index {
                0 => {
                    assert!(
                        request.starts_with("HEAD /download HTTP/1.1\r\n"),
                        "unexpected request {request_index}: {request:?}"
                    );
                    assert!(
                        !request_lower.contains("range: bytes="),
                        "unexpected Range header in request {request_index}: {request:?}"
                    );
                }
                1 => assert!(
                    request_lower.contains("range: bytes=2-"),
                    "expected resume Range header in request {request_index}: {request:?}"
                ),
                2 => {
                    assert!(
                        request.starts_with("HEAD /download HTTP/1.1\r\n"),
                        "unexpected request {request_index}: {request:?}"
                    );
                    assert!(
                        !request_lower.contains("range: bytes="),
                        "unexpected Range header in request {request_index}: {request:?}"
                    );
                }
                3 => {
                    assert!(
                        request.starts_with("GET /download HTTP/1.1\r\n"),
                        "unexpected request {request_index}: {request:?}"
                    );
                    assert!(
                        !request_lower.contains("range: bytes="),
                        "unexpected Range header in fresh request {request_index}: {request:?}"
                    );
                }
                _ => unreachable!(),
            }
            stream
                .write_all(
                    if matches!(request_index, 0 | 2) {
                        b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nContent-Disposition: attachment; filename=actual.txt\r\nConnection: close\r\n\r\n".as_slice()
                    } else {
                        b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nContent-Disposition: attachment; filename=actual.txt\r\nConnection: close\r\n\r\nabcd".as_slice()
                    },
                )
                .await
                .expect("write cannot-resume response");
        }
    });

    let directory = tempfile::tempdir().expect("create cannot-resume output directory");
    let output = directory.path().join("actual.txt");
    tokio::fs::write(&output, b"ab")
        .await
        .expect("create cannot-resume partial output");
    let control_path = ControlFile::control_path_for(&output);
    let mut control = ControlFile::open_or_create(&control_path, 4, 1)
        .await
        .expect("create cannot-resume control file");
    control.update_completed_length(2);
    control
        .save()
        .await
        .expect("save cannot-resume control file");

    let options = DownloadOptions {
        dir: Some(directory.path().to_string_lossy().into_owned()),
        continue_download: true,
        force_sequential: true,
        use_head: true,
        always_resume: false,
        ..DownloadOptions::default()
    };
    let uri = format!("http://{address}/download");
    let mut command = DownloadCommand::new(GroupId::new(1008), &uri, &options, None, None)
        .expect("create cannot-resume filename command");

    tokio::time::timeout(Duration::from_secs(5), command.execute())
        .await
        .expect("cannot-resume filename download should not hang")
        .expect("cannot-resume filename download should complete fresh");

    assert_eq!(tokio::fs::read(&output).await.unwrap(), b"abcd");
    assert!(!directory.path().join("actual.1.txt").exists());
    server
        .await
        .expect("cannot-resume filename fixture should finish");
}

#[tokio::test]
async fn invalid_content_disposition_falls_back_to_url_filename() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind invalid filename fixture");
    let address = listener
        .local_addr()
        .expect("read invalid filename fixture address");
    let server = tokio::spawn(async move {
        let (mut stream, _) = listener
            .accept()
            .await
            .expect("accept invalid filename request");
        let mut request = [0u8; 4096];
        let bytes = stream
            .read(&mut request)
            .await
            .expect("read invalid filename request");
        assert!(
            String::from_utf8_lossy(&request[..bytes])
                .starts_with("GET /fallback.bin HTTP/1.1\r\n")
        );
        stream
            .write_all(
                b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nContent-Disposition: attachment; filename=../escape.bin\r\nConnection: close\r\n\r\ndata",
            )
            .await
            .expect("write invalid filename response");
    });

    let directory = tempfile::tempdir().expect("create invalid filename directory");
    let options = DownloadOptions {
        dir: Some(directory.path().to_string_lossy().into_owned()),
        force_sequential: true,
        ..DownloadOptions::default()
    };
    let uri = format!("http://{address}/fallback.bin");
    let mut command = DownloadCommand::new(GroupId::new(1012), &uri, &options, None, None)
        .expect("create invalid filename command");

    tokio::time::timeout(Duration::from_secs(5), command.execute())
        .await
        .expect("invalid filename download should not hang")
        .expect("invalid filename download should complete");

    assert_eq!(
        tokio::fs::read(directory.path().join("fallback.bin"))
            .await
            .expect("read URL fallback output"),
        b"data"
    );
    assert!(!directory.path().join("escape.bin").exists());
    server
        .await
        .expect("invalid filename fixture should finish");
}

#[tokio::test]
async fn reserved_content_disposition_name_is_sanitized_before_download() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind reserved filename fixture");
    let address = listener
        .local_addr()
        .expect("read reserved filename fixture address");
    let server = tokio::spawn(async move {
        let (mut stream, _) = listener
            .accept()
            .await
            .expect("accept reserved filename request");
        let mut request = [0u8; 4096];
        let bytes = stream
            .read(&mut request)
            .await
            .expect("read reserved filename request");
        assert!(
            String::from_utf8_lossy(&request[..bytes]).starts_with("GET /download HTTP/1.1\r\n")
        );
        stream
            .write_all(
                b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\nContent-Disposition: attachment; filename=CON.txt\r\nConnection: close\r\n\r\ndata",
            )
            .await
            .expect("write reserved filename response");
    });

    let directory = tempfile::tempdir().expect("create reserved filename directory");
    let options = DownloadOptions {
        dir: Some(directory.path().to_string_lossy().into_owned()),
        force_sequential: true,
        ..DownloadOptions::default()
    };
    let uri = format!("http://{address}/download");
    let mut command = DownloadCommand::new(GroupId::new(1013), &uri, &options, None, None)
        .expect("create reserved filename command");

    tokio::time::timeout(Duration::from_secs(5), command.execute())
        .await
        .expect("reserved filename download should not hang")
        .expect("reserved filename download should complete");

    assert_eq!(
        tokio::fs::read(directory.path().join("_CON.txt"))
            .await
            .expect("read sanitized reserved output"),
        b"data"
    );
    assert!(!directory.path().join("CON.txt").exists());
    server
        .await
        .expect("reserved filename fixture should finish");
}

#[tokio::test]
async fn empty_control_and_long_content_disposition_names_are_safe_on_disk() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind filename edge-case fixture");
    let address = listener
        .local_addr()
        .expect("read filename edge-case fixture address");
    let encoded_long_name = crate::util::uri::percent_encode(&"界".repeat(100));
    let server = tokio::spawn(async move {
        for request_index in 0..3 {
            let (mut stream, _) = listener
                .accept()
                .await
                .expect("accept filename edge-case request");
            let mut request = [0u8; 4096];
            let bytes = stream
                .read(&mut request)
                .await
                .expect("read filename edge-case request");
            let request = String::from_utf8_lossy(&request[..bytes]);
            let expected_path = match request_index {
                0 => "/empty.bin",
                1 => "/control.bin",
                2 => "/long.bin",
                _ => unreachable!(),
            };
            assert!(request.starts_with(&format!("GET {expected_path} HTTP/1.1\r\n")));

            let response = match request_index {
                0 => b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nContent-Disposition: attachment; filename=\"\"\r\nConnection: close\r\n\r\none".to_vec(),
                1 => b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nContent-Disposition: attachment; filename*=UTF-8''bad%00name.txt\r\nConnection: close\r\n\r\ntwo".to_vec(),
                2 => format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: 3\r\nContent-Disposition: attachment; filename*=UTF-8''{encoded_long_name}\r\nConnection: close\r\n\r\ntri"
                )
                .into_bytes(),
                _ => unreachable!(),
            };
            stream
                .write_all(&response)
                .await
                .expect("write filename edge-case response");
        }
    });

    let directory = tempfile::tempdir().expect("create filename edge-case directory");
    let options = DownloadOptions {
        dir: Some(directory.path().to_string_lossy().into_owned()),
        force_sequential: true,
        ..DownloadOptions::default()
    };
    let cases = [
        (1014, "empty.bin", "empty.bin".to_owned(), b"one".as_slice()),
        (
            1015,
            "control.bin",
            "control.bin".to_owned(),
            b"two".as_slice(),
        ),
        (1016, "long.bin", "界".repeat(85), b"tri".as_slice()),
    ];
    for (gid, uri_path, output_name, expected_body) in cases {
        let uri = format!("http://{address}/{uri_path}");
        let mut command = DownloadCommand::new(GroupId::new(gid), &uri, &options, None, None)
            .expect("create filename edge-case command");
        tokio::time::timeout(Duration::from_secs(5), command.execute())
            .await
            .expect("filename edge-case download should not hang")
            .expect("filename edge-case download should complete");
        assert_eq!(
            tokio::fs::read(directory.path().join(output_name))
                .await
                .expect("read URL fallback filename"),
            expected_body
        );
    }

    assert!(!directory.path().join("bad").exists());
    assert!(!directory.path().join("name.txt").exists());
    server
        .await
        .expect("filename edge-case fixture should finish");
}