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
//! Integration and unit tests for the splice HTTP download module.
//!
//! Linux-only tests exercise the full splice download pipeline via a mock
//! HTTP server. Non-Linux tests verify the unsupported-platform stub.

// =========================================================================
// Linux tests
// =========================================================================

#[cfg(all(test, target_os = "linux"))]
mod linux_tests {
    use super::super::download::try_splice_download;
    use super::super::download::try_splice_download_with_policy;
    use super::super::helpers::{
        find_header_end, is_chunked, parse_content_length, parse_status_code, write_all_at_offset,
    };
    use std::io;
    use std::sync::Arc;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    /// Spawn a mock HTTP server that responds to a Range request with 206
    /// Partial Content. Returns the server address.
    ///
    /// The server sends `body[offset..offset+length]` as the response body
    /// with a Content-Length header.
    async fn spawn_mock_206_server(body: Vec<u8>) -> std::net::SocketAddr {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind mock server");
        let addr = listener.local_addr().expect("get mock server local addr");

        tokio::spawn(async move {
            let (mut sock, _) = listener
                .accept()
                .await
                .expect("mock server accept connection");

            // Read the request (until \r\n\r\n).
            let mut req_buf = [0u8; 4096];
            let _n = sock
                .read(&mut req_buf)
                .await
                .expect("mock server read request");

            // Parse the Range header from the request to determine what to send.
            let req_str = std::str::from_utf8(&req_buf).unwrap_or("");
            let (offset, length) = parse_request_range(req_str, body.len());

            let end = offset + length.saturating_sub(1);
            let chunk = &body[offset..offset + length.min(body.len() - offset)];

            let response = format!(
                "HTTP/1.1 206 Partial Content\r\n\
                 Content-Length: {}\r\n\
                 Content-Range: bytes {}-{}/{}\r\n\
                 Connection: close\r\n\
                 \r\n",
                chunk.len(),
                offset,
                end,
                body.len()
            );

            sock.write_all(response.as_bytes())
                .await
                .expect("mock server write headers");
            sock.write_all(chunk).await.expect("mock server write body");
        });

        addr
    }

    /// Parse `Range: bytes=START-END` from a raw HTTP request string.
    fn parse_request_range(req: &str, total: usize) -> (usize, usize) {
        for line in req.lines() {
            if let Some(rest) = line.strip_prefix("Range:") {
                let rest = rest.trim();
                if let Some(range) = rest.strip_prefix("bytes=")
                    && let Some((start_s, end_s)) = range.split_once('-')
                {
                    let start: usize = start_s.parse().unwrap_or(0);
                    let end: usize = end_s.parse().unwrap_or(total - 1);
                    let length = end.saturating_sub(start) + 1;
                    return (start, length);
                }
            }
        }
        (0, total)
    }

    #[tokio::test]
    async fn test_splice_download_basic() {
        // Create a payload and serve it via a mock HTTP server.
        let payload: Vec<u8> = (0..100_000u32).map(|i| (i % 256) as u8).collect();
        let addr = spawn_mock_206_server(payload.clone()).await;

        // Create output file.
        let dir = tempfile::tempdir().expect("create temp dir");
        let out_path = dir.path().join("out.bin");
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&out_path)
            .expect("create output file");

        let url = format!("http://{addr}/test.bin");
        let n = try_splice_download(&url, 0, payload.len() as u64, &file, 0)
            .await
            .expect("splice download should succeed");

        assert_eq!(n, payload.len() as u64);

        // Verify the file content matches the payload.
        drop(file);
        let content = std::fs::read(&out_path).expect("read output file");
        assert_eq!(content, payload);
    }

    #[tokio::test]
    async fn test_splice_download_uses_configured_source_address() {
        use crate::network::OutboundNetworkPolicy;

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind source-address splice server");
        let server_addr = listener
            .local_addr()
            .expect("read source-address splice server");
        let (peer_sender, peer_receiver) = tokio::sync::oneshot::channel();
        let payload = b"policy-bound splice body".to_vec();
        let server_payload = payload.clone();
        tokio::spawn(async move {
            let (mut socket, peer_addr) = listener
                .accept()
                .await
                .expect("accept source-address splice request");
            let _ = peer_sender.send(peer_addr);
            let mut request = [0u8; 4096];
            let _ = socket
                .read(&mut request)
                .await
                .expect("read source-address splice request");
            let response = format!(
                "HTTP/1.1 206 Partial Content\r\nContent-Length: {}\r\nContent-Range: bytes 0-{}/{}\r\nConnection: close\r\n\r\n",
                server_payload.len(),
                server_payload.len().saturating_sub(1),
                server_payload.len()
            );
            socket
                .write_all(response.as_bytes())
                .await
                .expect("write source-address splice headers");
            socket
                .write_all(&server_payload)
                .await
                .expect("write source-address splice body");
        });

        let directory = tempfile::tempdir().expect("create source-address splice directory");
        let output = directory.path().join("bound.bin");
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&output)
            .expect("create source-address splice output");
        let policy = Arc::new(OutboundNetworkPolicy::single(
            "127.0.0.2".parse().expect("loopback source address"),
        ));

        try_splice_download_with_policy(
            &format!("http://{server_addr}/bound.bin"),
            0,
            payload.len() as u64,
            &file,
            0,
            &policy,
        )
        .await
        .expect("policy-bound splice download should succeed");

        let peer_addr = peer_receiver
            .await
            .expect("source-address splice server should observe peer");
        assert_eq!(
            peer_addr.ip(),
            "127.0.0.2".parse::<std::net::IpAddr>().unwrap()
        );
    }

    #[tokio::test]
    async fn test_splice_download_range_offset() {
        // Download a sub-range starting at a non-zero offset.
        let payload: Vec<u8> = (0..200_000u32).map(|i| (i % 256) as u8).collect();
        let addr = spawn_mock_206_server(payload.clone()).await;

        let dir = tempfile::tempdir().expect("create temp dir");
        let out_path = dir.path().join("out_range.bin");
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&out_path)
            .expect("create output file");

        let offset = 50_000u64;
        let length = 80_000u64;
        let url = format!("http://{addr}/test.bin");
        let n = try_splice_download(&url, offset, length, &file, 0)
            .await
            .expect("splice range download should succeed");

        assert_eq!(n, length);

        // Verify the file content matches the requested sub-range.
        drop(file);
        let content = std::fs::read(&out_path).expect("read output file");
        assert_eq!(content.len(), length as usize);
        assert_eq!(
            content,
            &payload[offset as usize..(offset + length) as usize]
        );
    }

    #[tokio::test]
    async fn test_splice_download_with_file_offset() {
        // Splice data at a non-zero file offset (concurrent segment scenario).
        let payload: Vec<u8> = (0..64_000u32).map(|i| (i % 256) as u8).collect();
        let addr = spawn_mock_206_server(payload.clone()).await;

        let dir = tempfile::tempdir().expect("create temp dir");
        let out_path = dir.path().join("out_foff.bin");
        // Pre-allocate a larger file so pwrite at offset works.
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&out_path)
            .expect("create output file");
        file.set_len(100_000).expect("pre-allocate file");

        let file_offset = 30_000u64;
        let url = format!("http://{addr}/test.bin");
        let n = try_splice_download(&url, 0, payload.len() as u64, &file, file_offset)
            .await
            .expect("splice with file offset should succeed");

        assert_eq!(n, payload.len() as u64);

        // Verify the data was written at the correct offset.
        drop(file);
        let content = std::fs::read(&out_path).expect("read output file");
        assert_eq!(content.len(), 100_000);
        // The region before file_offset should be zero-filled.
        assert!(
            content[..file_offset as usize].iter().all(|&b| b == 0),
            "region before file_offset should be zero"
        );
        // The spliced region should match the payload.
        assert_eq!(
            &content[file_offset as usize..file_offset as usize + payload.len()],
            &payload[..]
        );
        // The region after should be zero-filled.
        assert!(
            content[file_offset as usize + payload.len()..]
                .iter()
                .all(|&b| b == 0),
            "region after spliced data should be zero"
        );
    }

    #[tokio::test]
    async fn test_splice_download_https_rejected() {
        let file = tempfile::tempfile().expect("create temp file");
        let result = try_splice_download("https://example.com/file", 0, 100, &file, 0).await;
        assert!(result.is_err());
        let err = result.expect_err("https should be rejected");
        assert_eq!(err.kind(), io::ErrorKind::Unsupported);
    }

    #[tokio::test]
    async fn test_splice_download_zero_length() {
        let file = tempfile::tempfile().expect("create temp file");
        let result = try_splice_download("http://example.com/file", 0, 0, &file, 0).await;
        assert!(result.is_ok());
        assert_eq!(result.expect("zero-length should return Ok"), 0);
    }

    #[tokio::test]
    async fn test_splice_download_non_206_falls_back() {
        // Server returns 200 (not 206) — splice should return Err so the
        // caller falls back to reqwest.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind test server");
        let addr = listener.local_addr().expect("get test server local addr");

        tokio::spawn(async move {
            let (mut sock, _) = listener
                .accept()
                .await
                .expect("test server accept connection");
            let mut buf = [0u8; 4096];
            let _ = sock.read(&mut buf).await.expect("test server read request");
            sock.write_all(
                b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: close\r\n\r\nhello",
            )
            .await
            .expect("test server write 200 response");
        });

        let dir = tempfile::tempdir().expect("create temp dir");
        let out_path = dir.path().join("out_200.bin");
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&out_path)
            .expect("create output file");

        let url = format!("http://{addr}/test.bin");
        let result = try_splice_download(&url, 0, 5, &file, 0).await;
        assert!(result.is_err(), "non-206 should return Err for fallback");
    }

    #[tokio::test]
    async fn test_splice_download_small_body_in_header_buffer() {
        // When the body fits entirely in the header read buffer (pre-read
        // path), verify it's written correctly via pwrite.
        let payload = b"tiny payload!".to_vec();
        let addr = spawn_mock_206_server(payload.clone()).await;

        let dir = tempfile::tempdir().expect("create temp dir");
        let out_path = dir.path().join("out_tiny.bin");
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&out_path)
            .expect("create output file");

        let url = format!("http://{addr}/test.bin");
        let n = try_splice_download(&url, 0, payload.len() as u64, &file, 0)
            .await
            .expect("splice tiny download should succeed");

        assert_eq!(n, payload.len() as u64);

        drop(file);
        let content = std::fs::read(&out_path).expect("read output file");
        assert_eq!(content, payload);
    }

    #[test]
    fn test_find_header_end() {
        assert_eq!(find_header_end(b""), None);
        assert_eq!(find_header_end(b"HTTP/1.1 200 OK\r\n"), None);
        assert_eq!(
            find_header_end(b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\n"),
            Some(34)
        );
        assert_eq!(find_header_end(b"HTTP/1.1 200 OK\r\n\r\nbody"), Some(15));
    }

    #[test]
    fn test_parse_status_code() {
        assert_eq!(
            parse_status_code("HTTP/1.1 206 Partial Content\r\n").expect("parse 206"),
            206
        );
        assert_eq!(
            parse_status_code("HTTP/1.1 200 OK\r\n").expect("parse 200"),
            200
        );
        assert!(parse_status_code("garbage").is_err());
        assert!(parse_status_code("").is_err());
    }

    #[test]
    fn test_is_chunked() {
        assert!(is_chunked(
            "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"
        ));
        assert!(is_chunked(
            "HTTP/1.1 200 OK\r\ntransfer-encoding: CHUNKED\r\n\r\n"
        ));
        assert!(!is_chunked(
            "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n"
        ));
    }

    #[test]
    fn test_parse_content_length() {
        assert_eq!(
            parse_content_length("HTTP/1.1 206\r\nContent-Length: 12345\r\n\r\n")
                .expect("parse content-length 12345"),
            Some(12345)
        );
        assert_eq!(
            parse_content_length("HTTP/1.1 206\r\ncontent-length: 0\r\n\r\n")
                .expect("parse content-length 0"),
            Some(0)
        );
        assert_eq!(
            parse_content_length("HTTP/1.1 206\r\n\r\n").expect("parse missing content-length"),
            None
        );
    }

    #[test]
    fn test_write_all_at_offset() {
        let dir = tempfile::tempdir().expect("create temp dir");
        let path = dir.path().join("pwrite_test.bin");
        let file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&path)
            .expect("create pwrite test file");
        file.set_len(100).expect("pre-allocate pwrite test file");

        write_all_at_offset(&file, b"hello", 10).expect("pwrite hello at offset 10");
        write_all_at_offset(&file, b"world", 50).expect("pwrite world at offset 50");

        drop(file);
        let content = std::fs::read(&path).expect("read pwrite test file");
        assert_eq!(&content[10..15], b"hello");
        assert_eq!(&content[50..55], b"world");
        assert_eq!(&content[0..10], &[0u8; 10]);
    }
}

// =========================================================================
// Non-Linux tests
// =========================================================================

/// Non-Linux test: verify the stub returns Err(Unsupported).
#[cfg(all(test, not(target_os = "linux")))]
mod non_linux_tests {
    use super::super::download::try_splice_download;
    use std::io;

    #[tokio::test]
    async fn test_splice_unsupported_on_non_linux() {
        let file = tempfile::tempfile().expect("create temp file");
        let result = try_splice_download("http://example.com/file", 0, 100, &file, 0).await;
        assert!(result.is_err());
        assert_eq!(
            result.expect_err("non-linux should return Err").kind(),
            io::ErrorKind::Unsupported
        );
    }
}