aria2-protocol 0.3.5

Multi-protocol networking stack for aria2-rust: HTTP/HTTPS client, FTP/SFTP, full BitTorrent (DHT/PEX/MSE), and Metalink V3/V4 parser
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
use std::collections::BTreeMap;

/// Maximum byte-string payload accepted by the bencode decoder.
///
/// This bounds allocations for untrusted torrent and extension metadata while
/// remaining well above normal torrent metadata sizes.
pub const MAX_BYTE_STRING_LENGTH: usize = 64 * 1024 * 1024;

/// Maximum nesting depth accepted by the decoder.
///
/// Mirrors the C++ `BencodeParser::pushState` guard (`stateStack_.size() >= 50`
/// -> `ERR_STRUCTURE_TOO_DEEP`). Without this limit a hostile `.torrent`
/// consisting of a long run of `l`/`d` opener bytes drives unbounded recursion
/// and aborts the process on stack overflow, which Rust cannot catch.
pub const MAX_NESTING_DEPTH: usize = 50;

/// Maximum number of direct elements accepted in one list or dictionary.
///
/// The count is based on wire entries, so duplicate dictionary keys still
/// consume the budget even though the decoded map keeps only the last value.
pub const MAX_CONTAINER_ELEMENTS: usize = 65_536;

#[derive(Debug, Clone, PartialEq)]
pub enum BencodeValue {
    Int(i64),
    Bytes(Vec<u8>),
    List(Vec<BencodeValue>),
    Dict(BTreeMap<Vec<u8>, BencodeValue>),
}

impl BencodeValue {
    pub fn decode(bytes: &[u8]) -> Result<(Self, usize), String> {
        Self::decode_at_depth(bytes, 0)
    }

    fn decode_at_depth(bytes: &[u8], depth: usize) -> Result<(Self, usize), String> {
        if bytes.is_empty() {
            return Err("Empty byte stream".to_string());
        }

        match bytes[0] {
            b'i' => Self::decode_int(bytes),
            b'l' => Self::decode_list(bytes, depth),
            b'd' => Self::decode_dict(bytes, depth),
            b'0'..=b'9' => Self::decode_bytes(bytes),
            c => Err(format!(
                "Invalid bencode start character: '{}' (0x{:02x})",
                c as char, c
            )),
        }
    }

    /// Returns the depth a nested container's children live at, or an error when
    /// the structure would exceed [`MAX_NESTING_DEPTH`].
    fn descend(depth: usize) -> Result<usize, String> {
        if depth >= MAX_NESTING_DEPTH {
            return Err(format!(
                "Bencode structure too deep: exceeds maximum nesting depth of {}",
                MAX_NESTING_DEPTH
            ));
        }
        Ok(depth + 1)
    }

    fn decode_int(bytes: &[u8]) -> Result<(Self, usize), String> {
        if !bytes.starts_with(b"i") {
            return Err("Integer does not start with 'i'".to_string());
        }
        let end = bytes
            .iter()
            .position(|&b| b == b'e')
            .ok_or("Integer missing end marker 'e'")?;
        if end <= 1 {
            return Err("Integer is empty".to_string());
        }
        let raw = &bytes[1..end];
        if (raw.len() > 1 && raw.first() == Some(&b'0'))
            || (raw.first() == Some(&b'-') && raw.get(1) == Some(&b'0'))
        {
            return Err("Integer is not canonically encoded".to_string());
        }
        let num_str = std::str::from_utf8(raw)
            .map_err(|e| format!("Integer content is not valid UTF-8: {}", e))?;
        let value: i64 = num_str
            .parse()
            .map_err(|e| format!("Failed to parse integer: {} (content: '{}')", e, num_str))?;
        Ok((BencodeValue::Int(value), end + 1))
    }

    fn decode_bytes(bytes: &[u8]) -> Result<(Self, usize), String> {
        let colon_pos = bytes
            .iter()
            .position(|&b| b == b':')
            .ok_or("Byte string missing length separator ':'")?;
        if colon_pos == 0 {
            return Err("Byte string length is empty".to_string());
        }
        let len_str = std::str::from_utf8(&bytes[..colon_pos])
            .map_err(|e| format!("Byte string length prefix is not valid UTF-8: {}", e))?;
        let length: usize = len_str
            .parse()
            .map_err(|e| format!("Failed to parse byte string length: {}", e))?;
        if length > MAX_BYTE_STRING_LENGTH {
            return Err(format!(
                "Byte string length {} exceeds maximum {}",
                length, MAX_BYTE_STRING_LENGTH
            ));
        }
        let data_start = colon_pos + 1;
        // `length` comes straight off the wire; a value near `usize::MAX` would
        // wrap on a plain add and make the bounds check below pass, then panic
        // inside the slice index. Reject the overflow explicitly instead.
        let data_end = data_start.checked_add(length).ok_or_else(|| {
            format!(
                "Byte string length overflows address space: declared length={}",
                length
            )
        })?;
        if data_end > bytes.len() {
            return Err(format!(
                "Byte string data insufficient: declared length={}, available={}",
                length,
                bytes.len() - data_start
            ));
        }
        Ok((
            BencodeValue::Bytes(bytes[data_start..data_end].to_vec()),
            data_end,
        ))
    }

    fn decode_list(bytes: &[u8], depth: usize) -> Result<(Self, usize), String> {
        if !bytes.starts_with(b"l") {
            return Err("List does not start with 'l'".to_string());
        }
        let inner_depth = Self::descend(depth)?;
        let mut pos = 1;
        let mut items = Vec::new();
        while pos < bytes.len() && bytes[pos] != b'e' {
            if items.len() >= MAX_CONTAINER_ELEMENTS {
                return Err(format!(
                    "List contains more than maximum {} elements",
                    MAX_CONTAINER_ELEMENTS
                ));
            }
            let (item, consumed) = Self::decode_at_depth(&bytes[pos..], inner_depth)?;
            items.push(item);
            pos += consumed;
        }
        if pos >= bytes.len() {
            return Err("List missing end marker 'e'".to_string());
        }
        Ok((BencodeValue::List(items), pos + 1))
    }

    fn decode_dict(bytes: &[u8], depth: usize) -> Result<(Self, usize), String> {
        if !bytes.starts_with(b"d") {
            return Err("Dictionary does not start with 'd'".to_string());
        }
        let inner_depth = Self::descend(depth)?;
        let mut pos = 1;
        let mut entries = BTreeMap::new();
        let mut element_count = 0;
        while pos < bytes.len() && bytes[pos] != b'e' {
            if element_count >= MAX_CONTAINER_ELEMENTS {
                return Err(format!(
                    "Dictionary contains more than maximum {} elements",
                    MAX_CONTAINER_ELEMENTS
                ));
            }
            let (key, key_consumed) = Self::decode_at_depth(&bytes[pos..], inner_depth)?;
            let key_bytes = match key {
                BencodeValue::Bytes(b) => b,
                _ => return Err("Dict key must be a byte string".to_string()),
            };
            pos += key_consumed;

            if pos >= bytes.len() || bytes[pos] == b'e' {
                return Err("Dict value missing (odd number of elements)".to_string());
            }
            let (value, val_consumed) = Self::decode_at_depth(&bytes[pos..], inner_depth)?;
            // Preserve the existing compatibility behavior: later duplicate
            // keys replace earlier values in the decoded map.
            entries.insert(key_bytes, value);
            element_count += 1;
            pos += val_consumed;
        }
        if pos >= bytes.len() {
            return Err("Dict missing end marker 'e'".to_string());
        }
        Ok((BencodeValue::Dict(entries), pos + 1))
    }

    pub fn encode(&self) -> Vec<u8> {
        match self {
            BencodeValue::Int(n) => format!("i{}e", n).into_bytes(),
            BencodeValue::Bytes(data) => {
                let mut result = format!("{}:", data.len()).into_bytes();
                result.extend_from_slice(data);
                result
            }
            BencodeValue::List(items) => {
                let mut result = vec![b'l'];
                for item in items {
                    result.extend(item.encode());
                }
                result.push(b'e');
                result
            }
            BencodeValue::Dict(entries) => {
                let mut result = vec![b'd'];
                for (key, value) in entries {
                    result.extend(format!("{}:", key.len()).into_bytes());
                    result.extend_from_slice(key);
                    result.extend(value.encode());
                }
                result.push(b'e');
                result
            }
        }
    }

    pub fn as_int(&self) -> Option<i64> {
        match self {
            BencodeValue::Int(n) => Some(*n),
            _ => None,
        }
    }

    pub fn as_bytes(&self) -> Option<&[u8]> {
        match self {
            BencodeValue::Bytes(b) => Some(b),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        self.as_bytes().and_then(|b| std::str::from_utf8(b).ok())
    }

    pub fn as_list(&self) -> Option<&Vec<BencodeValue>> {
        match self {
            BencodeValue::List(l) => Some(l),
            _ => None,
        }
    }

    pub fn as_dict(&self) -> Option<&BTreeMap<Vec<u8>, BencodeValue>> {
        match self {
            BencodeValue::Dict(d) => Some(d),
            _ => None,
        }
    }

    pub fn dict_get<K: AsRef<[u8]>>(&self, key: K) -> Option<&BencodeValue> {
        self.as_dict()?.get(key.as_ref())
    }

    pub fn dict_get_str(&self, key: &str) -> Option<&str> {
        self.dict_get(key.as_bytes()).and_then(|v| v.as_str())
    }

    pub fn dict_get_int(&self, key: &str) -> Option<i64> {
        self.dict_get(key.as_bytes()).and_then(|v| v.as_int())
    }

    pub fn is_int(&self) -> bool {
        matches!(self, BencodeValue::Int(_))
    }
    pub fn is_bytes(&self) -> bool {
        matches!(self, BencodeValue::Bytes(_))
    }
    pub fn is_list(&self) -> bool {
        matches!(self, BencodeValue::List(_))
    }
    pub fn is_dict(&self) -> bool {
        matches!(self, BencodeValue::Dict(_))
    }
}

impl From<i64> for BencodeValue {
    fn from(n: i64) -> Self {
        BencodeValue::Int(n)
    }
}

impl From<Vec<u8>> for BencodeValue {
    fn from(b: Vec<u8>) -> Self {
        BencodeValue::Bytes(b)
    }
}

impl From<String> for BencodeValue {
    fn from(s: String) -> Self {
        BencodeValue::Bytes(s.into_bytes())
    }
}

impl From<Vec<BencodeValue>> for BencodeValue {
    fn from(l: Vec<BencodeValue>) -> Self {
        BencodeValue::List(l)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encode_decode_int() {
        let original = BencodeValue::Int(42);
        let encoded = original.encode();
        let (decoded, _) = BencodeValue::decode(&encoded).unwrap();
        assert_eq!(original, decoded);

        assert_eq!(BencodeValue::decode(b"i0e"), Ok((BencodeValue::Int(0), 3)));
        assert_eq!(
            BencodeValue::decode(b"i-42e"),
            Ok((BencodeValue::Int(-42), 5))
        );
        assert_eq!(
            BencodeValue::decode(b"i123456789e"),
            Ok((BencodeValue::Int(123456789), 11))
        );
    }

    #[test]
    fn test_encode_decode_bytes() {
        let original = BencodeValue::Bytes(b"hello".to_vec());
        let encoded = original.encode();
        let (decoded, _) = BencodeValue::decode(&encoded).unwrap();
        assert_eq!(original, decoded);

        assert_eq!(
            BencodeValue::decode(b"4:spam"),
            Ok((BencodeValue::Bytes(b"spam".to_vec()), 6))
        );
        assert_eq!(
            BencodeValue::decode(b"0:"),
            Ok((BencodeValue::Bytes(vec![]), 2))
        );
        let binary_data: Vec<u8> = vec![0, 1, 2, 255];
        let enc = BencodeValue::Bytes(binary_data.clone()).encode();
        assert_eq!(
            BencodeValue::decode(&enc),
            Ok((BencodeValue::Bytes(binary_data), 6))
        );
    }

    #[test]
    fn test_encode_decode_list() {
        let list = BencodeValue::List(vec![
            BencodeValue::Int(1),
            BencodeValue::Bytes(b"two".to_vec()),
            BencodeValue::Int(3),
        ]);
        let encoded = list.encode();
        let (decoded, _) = BencodeValue::decode(&encoded).unwrap();
        assert_eq!(list, decoded);

        assert_eq!(
            BencodeValue::decode(b"le"),
            Ok((BencodeValue::List(vec![]), 2))
        );
    }

    #[test]
    fn test_encode_decode_dict() {
        let mut map = BTreeMap::new();
        map.insert(b"bar".to_vec(), BencodeValue::Bytes(b"spam".to_vec()));
        map.insert(b"foo".to_vec(), BencodeValue::Int(42));
        let dict = BencodeValue::Dict(map);
        let encoded = dict.encode();
        let (decoded, _) = BencodeValue::decode(&encoded).unwrap();
        assert_eq!(dict, decoded);

        assert_eq!(
            BencodeValue::decode(b"de"),
            Ok((BencodeValue::Dict(BTreeMap::new()), 2))
        );
    }

    #[test]
    fn test_nested_structures() {
        let nested = BencodeValue::Dict({
            let mut m = BTreeMap::new();
            m.insert(
                b"a".to_vec(),
                BencodeValue::List(vec![BencodeValue::Dict({
                    let mut inner = BTreeMap::new();
                    inner.insert(b"x".to_vec(), BencodeValue::Int(99));
                    inner
                })]),
            );
            m
        });
        let encoded = nested.encode();
        let (decoded, _) = BencodeValue::decode(&encoded).unwrap();
        assert_eq!(nested, decoded);
    }

    #[test]
    fn test_type_accessors() {
        let v = BencodeValue::Int(100);
        assert_eq!(v.as_int(), Some(100));
        assert!(v.as_str().is_none());

        let v = BencodeValue::Bytes(b"hello".to_vec());
        assert_eq!(v.as_str(), Some("hello"));
        assert!(v.as_int().is_none());

        let mut d = BTreeMap::new();
        d.insert(b"key".to_vec(), BencodeValue::Int(42));
        let v = BencodeValue::Dict(d);
        assert_eq!(v.dict_get_int("key"), Some(42));
        assert!(v.dict_get_str("missing").is_none());
    }

    #[test]
    fn test_error_cases() {
        assert!(BencodeValue::decode(b"").is_err());
        assert!(BencodeValue::decode(b"ie").is_err());
        assert!(BencodeValue::decode(b"i").is_err());
        assert!(BencodeValue::decode(b":hello").is_err());
        assert!(BencodeValue::decode(b"5:hi").is_err());
        assert!(BencodeValue::decode(b"l").is_err());
        assert!(BencodeValue::decode(b"d").is_err());
        assert!(BencodeValue::decode(b"d3:key").is_err());
        assert!(BencodeValue::decode(b"i01e").is_err());
        assert!(BencodeValue::decode(b"i-0e").is_err());
    }

    #[test]
    fn test_partial_decode() {
        let input = b"i42e4:test";
        let (val, consumed) = BencodeValue::decode(input).unwrap();
        assert_eq!(val, BencodeValue::Int(42));
        assert_eq!(consumed, 4);
        assert_eq!(&input[consumed..], b"4:test");
    }

    /// Builds `open`-repeated ... `e`-repeated, e.g. depth 3 with `l` => "llleee".
    fn nested(open: u8, depth: usize) -> Vec<u8> {
        let mut v = vec![open; depth];
        v.extend(std::iter::repeat_n(b'e', depth));
        v
    }

    #[test]
    fn test_nesting_at_limit_is_accepted() {
        let input = nested(b'l', MAX_NESTING_DEPTH);
        assert!(
            BencodeValue::decode(&input).is_ok(),
            "exactly MAX_NESTING_DEPTH levels must still parse"
        );
    }

    #[test]
    fn test_nesting_beyond_limit_is_rejected() {
        let input = nested(b'l', MAX_NESTING_DEPTH + 1);
        let err = BencodeValue::decode(&input).unwrap_err();
        assert!(err.contains("too deep"), "unexpected error: {err}");
    }

    #[test]
    fn test_dict_nesting_beyond_limit_is_rejected() {
        // d1:a d1:a ... i0e e...e  -- nest dictionaries through their values.
        let depth = MAX_NESTING_DEPTH + 5;
        let mut input = Vec::new();
        for _ in 0..depth {
            input.extend_from_slice(b"d1:a");
        }
        input.extend_from_slice(b"i0e");
        input.extend(std::iter::repeat_n(b'e', depth));
        let err = BencodeValue::decode(&input).unwrap_err();
        assert!(err.contains("too deep"), "unexpected error: {err}");
    }

    #[test]
    fn test_container_element_limit_is_enforced() {
        let mut list = vec![b'l'];
        for _ in 0..MAX_CONTAINER_ELEMENTS {
            list.extend_from_slice(b"i0e");
        }
        list.push(b'e');
        assert!(BencodeValue::decode(&list).is_ok());

        list.insert(1, b'i');
        list.insert(2, b'0');
        list.insert(3, b'e');
        let err = BencodeValue::decode(&list).unwrap_err();
        assert!(err.contains("maximum"), "unexpected error: {err}");

        let mut dict = b"d".to_vec();
        for _ in 0..=MAX_CONTAINER_ELEMENTS {
            dict.extend_from_slice(b"1:ai0e");
        }
        dict.push(b'e');
        let err = BencodeValue::decode(&dict).unwrap_err();
        assert!(err.contains("maximum"), "unexpected error: {err}");
    }

    /// A hostile torrent used to abort the process via stack overflow here.
    #[test]
    fn test_pathological_nesting_does_not_overflow_stack() {
        let input = vec![b'l'; 200_000];
        let err = BencodeValue::decode(&input).unwrap_err();
        assert!(err.contains("too deep"), "unexpected error: {err}");
    }

    #[test]
    fn test_byte_string_length_overflow_is_rejected() {
        // `usize::MAX` as the length prefix wrapped the `data_start + length`
        // add and panicked inside the slice index before the checked_add fix.
        let input = format!("{}:", usize::MAX).into_bytes();
        let err = BencodeValue::decode(&input).unwrap_err();
        assert!(
            err.contains("exceeds maximum")
                || err.contains("overflow")
                || err.contains("insufficient"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_byte_string_above_allocation_limit_is_rejected() {
        let input = format!("{}:", MAX_BYTE_STRING_LENGTH + 1);
        let err = BencodeValue::decode(input.as_bytes()).unwrap_err();
        assert!(err.contains("exceeds maximum"), "unexpected error: {err}");
    }
}