aria2-protocol 0.3.10

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
//! Semantic validation for parsed BitTorrent peer messages.
//!
//! While `parse_message()` validates structural integrity (correct length, valid
//! message type), this module provides domain-level validation that checks
//! constraints such as piece index bounds, block range validity, bitfield length
//! consistency, and info-hash matching. This is protocol validation against
//! torrent geometry; download scheduling and piece policy remain in core.

use std::fmt;

use crate::bittorrent::message::types::BtMessage;

/// Message received without the peer capability required to send it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PeerMessageCapabilityError {
    FastExtensionNotNegotiated,
    ExtendedMessagingNotNegotiated,
}

impl fmt::Display for PeerMessageCapabilityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::FastExtensionNotNegotiated => {
                f.write_str("peer sent a Fast Extension message without negotiating Fast Extension")
            }
            Self::ExtendedMessagingNotNegotiated => {
                f.write_str("peer sent an extended message without negotiating extended messaging")
            }
        }
    }
}

impl std::error::Error for PeerMessageCapabilityError {}

/// Validate that a message is permitted by the capabilities in the peer handshake.
pub fn validate_message_capabilities(
    message: &BtMessage,
    supports_fast_extension: bool,
    supports_extended_messaging: bool,
) -> Result<(), PeerMessageCapabilityError> {
    if matches!(
        message,
        BtMessage::AllowedFast { .. }
            | BtMessage::Reject { .. }
            | BtMessage::HaveAll
            | BtMessage::HaveNone
    ) && !supports_fast_extension
    {
        return Err(PeerMessageCapabilityError::FastExtensionNotNegotiated);
    }
    if matches!(message, BtMessage::Extended { .. }) && !supports_extended_messaging {
        return Err(PeerMessageCapabilityError::ExtendedMessagingNotNegotiated);
    }
    Ok(())
}

/// Maximum block length (64 KiB), matching C++ aria2 `BtConstants.h` `MAX_BLOCK_LENGTH`.
///
/// Note: While aria2 typically *requests* 16 KiB blocks (`BLOCK_SIZE`), the
/// protocol allows peers to send blocks up to 64 KiB. Using 16 KiB here would
/// incorrectly reject valid Piece/Request messages with larger blocks.
pub const MAX_BLOCK_LENGTH: u32 = 64 * 1024;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors produced by [`BtMessageValidator`] when a message fails domain
/// validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BtMessageValidationError {
    /// Piece index exceeds the total number of pieces in the torrent.
    IndexOutOfRange { index: u32, num_pieces: u32 },
    /// `begin + length` exceeds the piece length for the given piece index.
    BlockOutOfRange {
        index: u32,
        begin: u32,
        length: u32,
        piece_length: u32,
    },
    /// Bitfield byte count does not match the expected number of pieces.
    BitfieldLengthMismatch {
        bitfield_len: usize,
        expected_pieces: u32,
    },
    /// Received info-hash does not match the expected hash.
    InfoHashMismatch,
    /// Block length exceeds the configured maximum.
    InvalidBlockLength { length: u32, max_block_length: u32 },
}

impl fmt::Display for BtMessageValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IndexOutOfRange { index, num_pieces } => {
                write!(
                    f,
                    "piece index {} out of range (num_pieces={})",
                    index, num_pieces
                )
            }
            Self::BlockOutOfRange {
                index,
                begin,
                length,
                piece_length,
            } => {
                write!(
                    f,
                    "block out of range: index={}, begin={}, length={}, piece_length={}",
                    index, begin, length, piece_length
                )
            }
            Self::BitfieldLengthMismatch {
                bitfield_len,
                expected_pieces,
            } => {
                let expected_bytes = (*expected_pieces as usize).div_ceil(8);
                write!(
                    f,
                    "bitfield length {} does not match expected {} bytes ({} pieces)",
                    bitfield_len, expected_bytes, expected_pieces
                )
            }
            Self::InfoHashMismatch => write!(f, "info-hash mismatch"),
            Self::InvalidBlockLength {
                length,
                max_block_length,
            } => {
                write!(
                    f,
                    "block length {} exceeds maximum {}",
                    length, max_block_length
                )
            }
        }
    }
}

impl std::error::Error for BtMessageValidationError {}

// ---------------------------------------------------------------------------
// Validator
// ---------------------------------------------------------------------------

/// Domain-level validator for BitTorrent peer messages.
///
/// Construct with the torrent metadata (`num_pieces`, `piece_length`) and
/// optionally configure an expected info-hash or metadata-get mode.
/// It checks a parsed protocol message against active torrent geometry rather
/// than parsing wire bytes.
///
/// # Example
///
/// ```
/// use aria2_protocol::bittorrent::peer::message_validation::BtMessageValidator;
///
/// let validator = BtMessageValidator::new(1000, 262144)
///     .with_expected_info_hash([0u8; 20]);
///
/// assert!(validator.validate_index(500).is_ok());
/// assert!(validator.validate_index(2000).is_err());
/// ```
#[derive(Debug, Clone)]
pub struct BtMessageValidator {
    /// Total number of pieces in the torrent.
    pub num_pieces: u32,
    /// Byte length of each piece (the last piece may be shorter).
    pub piece_length: u32,
    /// Maximum allowed block length (default 64 KiB).
    pub max_block_length: u32,
    /// Expected info-hash for handshake validation.
    pub expected_info_hash: Option<[u8; 20]>,
    /// When true, skip piece/bitfield validation (metadata-only downloads
    /// where num_pieces/piece_length may not be meaningful).
    pub metadata_get_mode: bool,
}

impl BtMessageValidator {
    /// Create a new validator with the given torrent parameters.
    ///
    /// `max_block_length` defaults to [`MAX_BLOCK_LENGTH`] (64 KiB).
    /// `expected_info_hash` defaults to `None`.
    /// `metadata_get_mode` defaults to `false`.
    pub fn new(num_pieces: u32, piece_length: u32) -> Self {
        Self {
            num_pieces,
            piece_length,
            max_block_length: MAX_BLOCK_LENGTH,
            expected_info_hash: None,
            metadata_get_mode: false,
        }
    }

    /// Set the expected info-hash for handshake validation.
    pub fn with_expected_info_hash(mut self, hash: [u8; 20]) -> Self {
        self.expected_info_hash = Some(hash);
        self
    }

    /// Enable or disable metadata-get mode.
    ///
    /// When enabled, piece index, block range, and bitfield validations are
    /// skipped because `num_pieces` / `piece_length` may not reflect the
    /// actual torrent data (the peer is only fetching metadata).
    pub fn with_metadata_get_mode(mut self, mode: bool) -> Self {
        self.metadata_get_mode = mode;
        self
    }

    // -----------------------------------------------------------------------
    // Top-level dispatch
    // -----------------------------------------------------------------------

    /// Validate a parsed [`BtMessage`] against domain constraints.
    ///
    /// Messages that carry no domain payload (KeepAlive, Choke, Unchoke,
    /// Interested, NotInterested, HaveAll, HaveNone, Port, Extended) always
    /// pass validation.
    pub fn validate(&self, msg: &BtMessage) -> Result<(), BtMessageValidationError> {
        match msg {
            BtMessage::Have { piece_index } => self.validate_index(*piece_index),
            BtMessage::Bitfield { data } => self.validate_bitfield(data),
            BtMessage::Request { request } => {
                self.validate_range(request.index, request.begin, request.length)
            }
            BtMessage::Piece { index, begin, data } => {
                self.validate_piece(*index, *begin, data.len())
            }
            BtMessage::Cancel { request } => {
                self.validate_range(request.index, request.begin, request.length)
            }
            BtMessage::Reject {
                index,
                offset,
                length,
            } => self.validate_range(*index, *offset, *length),
            BtMessage::AllowedFast { index } => self.validate_index(*index),
            BtMessage::Suggest { index } => self.validate_index(*index),
            // No domain constraints to validate for these variants.
            BtMessage::KeepAlive
            | BtMessage::Choke
            | BtMessage::Unchoke
            | BtMessage::Interested
            | BtMessage::NotInterested
            | BtMessage::HaveAll
            | BtMessage::HaveNone
            | BtMessage::Port { .. }
            | BtMessage::Extended { .. } => Ok(()),
        }
    }

    // -----------------------------------------------------------------------
    // Per-constraint validation
    // -----------------------------------------------------------------------

    /// Validate a piece index (used for Have, SuggestPiece, AllowedFast).
    pub fn validate_index(&self, index: u32) -> Result<(), BtMessageValidationError> {
        if self.metadata_get_mode {
            return Ok(());
        }
        if index >= self.num_pieces {
            return Err(BtMessageValidationError::IndexOutOfRange {
                index,
                num_pieces: self.num_pieces,
            });
        }
        Ok(())
    }

    /// Validate a block range (used for Request, Cancel, Reject).
    ///
    /// Checks:
    /// 1. `index < num_pieces`
    /// 2. `length != 0` (C++ `checkLength` rejects zero-length blocks)
    /// 3. `begin + length <= piece_length` (with overflow protection)
    /// 4. `length <= max_block_length`
    pub fn validate_range(
        &self,
        index: u32,
        begin: u32,
        length: u32,
    ) -> Result<(), BtMessageValidationError> {
        if self.metadata_get_mode {
            return Ok(());
        }
        self.validate_index(index)?;
        // C++ checkLength rejects length == 0 for Request/Cancel/Reject.
        if length == 0 {
            return Err(BtMessageValidationError::BlockOutOfRange {
                index,
                begin,
                length: 0,
                piece_length: self.piece_length,
            });
        }
        // Overflow-safe addition: if begin + length overflows u32 it is
        // certainly larger than piece_length.
        let end = begin.checked_add(length);
        match end {
            Some(e) if e <= self.piece_length => {}
            _ => {
                return Err(BtMessageValidationError::BlockOutOfRange {
                    index,
                    begin,
                    length,
                    piece_length: self.piece_length,
                });
            }
        }
        if length > self.max_block_length {
            return Err(BtMessageValidationError::InvalidBlockLength {
                length,
                max_block_length: self.max_block_length,
            });
        }
        Ok(())
    }

    /// Validate a Piece message's data block.
    ///
    /// The same checks as [`Self::validate_range`] but using the actual data length
    /// (which may differ from the requested length for the final block of a
    /// piece).
    pub fn validate_piece(
        &self,
        index: u32,
        begin: u32,
        data_len: usize,
    ) -> Result<(), BtMessageValidationError> {
        if self.metadata_get_mode {
            return Ok(());
        }
        self.validate_index(index)?;
        let length = u32::try_from(data_len).unwrap_or(u32::MAX);
        if length == 0 {
            return Err(BtMessageValidationError::BlockOutOfRange {
                index,
                begin,
                length: 0,
                piece_length: self.piece_length,
            });
        }
        let end = begin.checked_add(length);
        match end {
            Some(e) if e <= self.piece_length => {}
            _ => {
                return Err(BtMessageValidationError::BlockOutOfRange {
                    index,
                    begin,
                    length,
                    piece_length: self.piece_length,
                });
            }
        }
        // Piece messages are allowed to carry up to max_block_length bytes.
        // The final block of a piece may be shorter, so we only reject
        // blocks that exceed the maximum.
        if length > self.max_block_length {
            return Err(BtMessageValidationError::InvalidBlockLength {
                length,
                max_block_length: self.max_block_length,
            });
        }
        Ok(())
    }

    /// Validate a Bitfield message's payload length.
    ///
    /// The bitfield must be exactly `ceil(num_pieces / 8)` bytes long.
    /// Additionally, unused bits in the last byte must be zero (C++ `checkBitfield`).
    pub fn validate_bitfield(&self, data: &[u8]) -> Result<(), BtMessageValidationError> {
        if self.metadata_get_mode {
            return Ok(());
        }
        let expected_bytes = (self.num_pieces as usize).div_ceil(8);
        if data.len() != expected_bytes {
            return Err(BtMessageValidationError::BitfieldLengthMismatch {
                bitfield_len: data.len(),
                expected_pieces: self.num_pieces,
            });
        }
        // C++ checkBitfield: verify that unused bits in the last byte are zero.
        // If num_pieces is not a multiple of 8, the last byte has some
        // unused low bits that must be zero because BitTorrent numbers bits
        // from the most significant bit.
        let remainder = (self.num_pieces as usize) % 8;
        if remainder != 0
            && let Some(&last_byte) = data.last()
        {
            // The valid bits in the last byte are the high `remainder` bits.
            // All lower bits must be zero.
            let mask: u8 = (1 << (8 - remainder)) - 1;
            if last_byte & mask != 0 {
                return Err(BtMessageValidationError::BitfieldLengthMismatch {
                    bitfield_len: data.len(),
                    expected_pieces: self.num_pieces,
                });
            }
        }
        Ok(())
    }

    /// Validate a Handshake message's info-hash.
    ///
    /// If no expected info-hash has been configured, validation always passes.
    pub fn validate_handshake(
        &self,
        received_hash: &[u8; 20],
    ) -> Result<(), BtMessageValidationError> {
        if let Some(expected) = self.expected_info_hash
            && received_hash != &expected
        {
            return Err(BtMessageValidationError::InfoHashMismatch);
        }
        Ok(())
    }
}

#[cfg(test)]
#[path = "message_validation_tests.rs"]
mod tests;