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
//! Torrent-specific state for one BitTorrent peer protocol session.
use std::collections::HashMap;
use crate::bittorrent::peer::message_validation::{BtMessageValidationError, BtMessageValidator};
/// Per-session resource for an active BitTorrent peer connection.
///
/// Contains peer availability, negotiated extensions, and message-validation
/// state for the active torrent geometry.
pub struct PeerSessionResource {
/// Bitfield tracking which pieces this peer has.
bitfield: Vec<u8>,
/// Bitfield length in bytes.
bitfield_length: usize,
/// Piece length for the torrent.
piece_length: u32,
/// Total length of the torrent.
total_length: u64,
/// Number of pieces in the torrent.
num_pieces: u32,
/// Validator reused by the peer connection read path.
message_validator: BtMessageValidator,
// Fast Extension (BEP 6)
/// Whether fast extension is enabled for this peer.
fast_extension_enabled: bool,
// Extension Protocol (BEP 10)
/// Extension IDs negotiated with this peer: name -> message ID.
peer_extensions: HashMap<Box<str>, u8>,
}
impl PeerSessionResource {
/// Create a new `PeerSessionResource` for the explicit torrent geometry.
///
/// `num_pieces` is authoritative because BEP 52 v2 multi-file torrents
/// can have aligned piece space larger than their content length.
pub fn new(piece_length: u32, num_pieces: u32, total_length: u64) -> Self {
let bitfield_length = (num_pieces as usize).div_ceil(8);
Self {
bitfield: vec![0u8; bitfield_length],
bitfield_length,
piece_length,
total_length,
num_pieces,
message_validator: BtMessageValidator::new(num_pieces, piece_length),
fast_extension_enabled: false,
peer_extensions: HashMap::new(),
}
}
// -----------------------------------------------------------------------
// Bitfield
// -----------------------------------------------------------------------
/// Check whether the peer has a given piece.
///
/// Returns `false` if the index is out of range or the bitfield is
/// too short.
pub fn has_piece(&self, index: usize) -> bool {
if index >= self.num_pieces as usize {
return false;
}
let byte = index / 8;
let bit = 7 - index % 8;
self.bitfield
.get(byte)
.is_some_and(|value| value & (1 << bit) != 0)
}
/// Set the peer bitfield from raw bytes.
///
/// Copies `bitfield` into the internal storage, truncating or
/// zero-extending as needed.
pub fn set_bitfield(&mut self, bitfield: &[u8]) -> Vec<u8> {
let old = self.bitfield.clone();
let copy_len = std::cmp::min(bitfield.len(), self.bitfield.len());
self.bitfield[..copy_len].copy_from_slice(&bitfield[..copy_len]);
// Zero-fill remaining bytes if source is shorter
self.bitfield[copy_len..].fill(0);
old
}
/// Update the peer bitfield: set (operation=1) or clear (operation=0)
/// the bit at `index`.
pub fn update_bitfield(&mut self, index: usize, operation: i32) {
if index >= self.num_pieces as usize {
return;
}
let byte = index / 8;
let bit = 7 - (index % 8);
if byte >= self.bitfield.len() {
return;
}
if operation == 1 {
self.bitfield[byte] |= 1 << bit;
} else {
self.bitfield[byte] &= !(1 << bit);
}
}
/// Mark all pieces as available (seeder bitfield).
fn set_all_bitfield(&mut self) {
self.bitfield.fill(0xFF);
// Clear trailing bits beyond num_pieces
let remaining = (self.num_pieces as usize) % 8;
if remaining != 0 {
let extra = 8 - remaining;
if let Some(last) = self.bitfield.last_mut() {
*last &= !((1u8 << extra) - 1);
}
}
}
/// Mark the peer as a seeder (has all pieces).
pub fn mark_seeder(&mut self) {
self.set_all_bitfield();
}
/// Check whether the peer is a seeder (has all pieces).
pub fn is_seeder(&self) -> bool {
// Count set bits and compare with num_pieces
let mut count = 0usize;
for &byte in &self.bitfield {
count += byte.count_ones() as usize;
}
// Adjust for trailing bits
let remaining = (self.num_pieces as usize) % 8;
if remaining != 0 && !self.bitfield.is_empty() {
let extra = 8 - remaining;
if let Some(&last) = self.bitfield.last() {
let trailing = (last & ((1u8 << extra) - 1)).count_ones() as usize;
count -= trailing;
}
}
count == self.num_pieces as usize
}
/// Get a reference to the raw bitfield bytes.
pub fn bitfield(&self) -> &[u8] {
&self.bitfield
}
/// Return the bitfield length in bytes.
pub fn bitfield_length(&self) -> usize {
self.bitfield_length
}
/// Reconfigure the session resource for new torrent geometry.
///
/// Called when the torrent metadata is updated (e.g., after magnet
/// link metadata exchange).
pub fn reconfigure(&mut self, piece_length: u32, num_pieces: u32, total_length: u64) {
let bitfield_length = (num_pieces as usize).div_ceil(8);
self.bitfield.resize(bitfield_length, 0);
self.bitfield_length = bitfield_length;
self.piece_length = piece_length;
self.total_length = total_length;
self.num_pieces = num_pieces;
self.message_validator = BtMessageValidator::new(num_pieces, piece_length);
}
/// Validate a parsed peer message against this torrent's geometry.
pub fn validate_message(
&self,
message: &crate::bittorrent::message::types::BtMessage,
) -> Result<(), BtMessageValidationError> {
self.message_validator.validate(message)
}
/// Get the number of pieces.
pub fn num_pieces(&self) -> u32 {
self.num_pieces
}
/// Get the piece length.
pub fn piece_length(&self) -> u32 {
self.piece_length
}
/// Get the total length.
pub fn total_length(&self) -> u64 {
self.total_length
}
// -----------------------------------------------------------------------
// Fast Extension (BEP 6)
// -----------------------------------------------------------------------
/// Enable or disable fast extension.
pub fn set_fast_extension_enabled(&mut self, enabled: bool) {
self.fast_extension_enabled = enabled;
}
/// Check whether fast extension is enabled.
pub fn is_fast_extension_enabled(&self) -> bool {
self.fast_extension_enabled
}
// -----------------------------------------------------------------------
// Extension Protocol (BEP 10)
// -----------------------------------------------------------------------
/// Apply a peer's BEP 10 extension ID update.
///
/// An ID of zero disables the extension, so disabled extensions are
/// removed rather than exposed as an active `Some(0)` mapping.
pub fn add_extension(&mut self, key: &str, id: u8) {
if id == 0 {
self.peer_extensions.remove(key);
} else {
self.peer_extensions.insert(key.into(), id);
}
}
/// Apply the peer's BEP 10 extension IDs to this protocol session.
pub fn apply_extension_handshake(
&mut self,
handshake: &crate::bittorrent::message::extension::ExtensionHandshake,
) {
if let Some(id) = handshake.ut_metadata_id() {
self.add_extension("ut_metadata", id);
}
if let Some(id) = handshake.ut_pex_id() {
self.add_extension("ut_pex", id);
}
}
/// Look up the message ID for a given extension key.
pub fn get_extension_message_id(&self, key: &str) -> Option<u8> {
self.peer_extensions.get(key).copied()
}
}