aria2-protocol 0.3.7

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
//! DHT K-bucket — holds up to K nodes for a specific ID range.
//!
//! Each bucket covers a contiguous range of DHT node IDs [min_id, max_id]
//! (inclusive) and holds up to `K` nodes that fall within that range. When
//! the bucket is full and contains the local node's ID, it can be split
//! into two halves.
//!
//! A replacement cache (`CACHE_SIZE = 2`) stores candidate nodes that can
//! replace questionable nodes in the main bucket. This is the Rust
//! equivalent of C++ `DHTBucket`.

use std::time::Instant;

use super::node::DhtNode;

/// K-bucket constant: maximum nodes per bucket (BEP 5).
pub const K: usize = 8;

/// Maximum replacement cache entries per bucket.
pub const CACHE_SIZE: usize = 2;

/// DHT ID length in bytes.
const ID_LENGTH: usize = 20;

/// Bucket refresh interval in seconds (15 minutes, matching C++ DHT_BUCKET_REFRESH_INTERVAL).
const BUCKET_REFRESH_INTERVAL_SECS: u64 = 15 * 60;

// ---------------------------------------------------------------------------
// Bit manipulation helpers
// ---------------------------------------------------------------------------

/// Flip the bit at `bit_index` (0 = MSB of byte 0, 159 = LSB of byte 19)
/// in the given ID buffer.
fn flip_bit(id: &mut [u8; 20], bit_index: usize) {
    let byte_index = bit_index / 8;
    let bit_offset = 7 - (bit_index % 8);
    if byte_index < 20 {
        id[byte_index] ^= 1 << bit_offset;
    }
}

// ---------------------------------------------------------------------------
// Bucket
// ---------------------------------------------------------------------------

/// A Kademlia DHT k-bucket holding nodes for a specific ID range.
///
/// Each bucket covers IDs in the range `[min_id, max_id]` (inclusive) and
/// can hold up to `K` nodes. When the bucket is full, only a verified good
/// candidate may replace a bad LRU node; other candidates are rejected.
///
/// Buckets also maintain a replacement cache of up to `CACHE_SIZE` nodes
/// that can be promoted when existing nodes become unresponsive.
#[derive(Debug)]
pub struct Bucket {
    /// Prefix length for this bucket (number of leading bits that are fixed).
    prefix_length: usize,

    /// Minimum ID in this bucket's range (inclusive).
    min_id: [u8; 20],

    /// Maximum ID in this bucket's range (inclusive).
    max_id: [u8; 20],

    /// The local node's ID (used to determine if splitting is allowed).
    local_id: [u8; 20],

    /// Nodes in this bucket, sorted by last-seen time (LRU at front).
    nodes: Vec<DhtNode>,

    /// Replacement cache, sorted by last-seen time (most recent at front).
    cached_nodes: Vec<DhtNode>,

    /// Time of last update to this bucket.
    last_updated: Instant,
}

impl Bucket {
    /// Create a new bucket covering the full ID space [0x00.., 0xFF..].
    ///
    /// This is the initial bucket that will be split as the routing table
    /// grows. Equivalent to C++ `DHTBucket(localNode)`.
    pub fn new(local_node: &DhtNode) -> Self {
        Self {
            prefix_length: 0,
            min_id: [0u8; 20],
            max_id: [0xFFu8; 20],
            local_id: local_node.id,
            nodes: Vec::with_capacity(K),
            cached_nodes: Vec::with_capacity(CACHE_SIZE),
            last_updated: Instant::now(),
        }
    }

    /// Create a bucket with a specific ID range and prefix length.
    ///
    /// Equivalent to C++ `DHTBucket(prefixLength, max, min, localNode)`.
    pub fn new_for_range(
        prefix_length: usize,
        min_id: [u8; 20],
        max_id: [u8; 20],
        local_id: [u8; 20],
    ) -> Self {
        Self {
            prefix_length,
            min_id,
            max_id,
            local_id,
            nodes: Vec::with_capacity(K),
            cached_nodes: Vec::with_capacity(CACHE_SIZE),
            last_updated: Instant::now(),
        }
    }

    // -----------------------------------------------------------------------
    // Accessors
    // -----------------------------------------------------------------------

    /// Returns the prefix length (number of fixed leading bits).
    pub fn prefix_length(&self) -> usize {
        self.prefix_length
    }

    /// Returns the minimum ID in this bucket's range.
    pub fn min_id(&self) -> &[u8; 20] {
        &self.min_id
    }

    /// Returns the maximum ID in this bucket's range.
    pub fn max_id(&self) -> &[u8; 20] {
        &self.max_id
    }

    /// Returns the number of nodes in this bucket.
    pub fn count_node(&self) -> usize {
        self.nodes.len()
    }

    /// Returns `true` if the bucket has reached its maximum capacity (K).
    pub fn is_full(&self) -> bool {
        self.nodes.len() >= K
    }

    /// Returns `true` if the bucket has no nodes.
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// Returns a reference to the nodes in this bucket.
    pub fn nodes(&self) -> &[DhtNode] {
        &self.nodes
    }

    /// Returns a reference to the replacement cache.
    pub fn cached_nodes(&self) -> &[DhtNode] {
        &self.cached_nodes
    }

    /// Returns the number of recently verified good nodes.
    pub fn good_node_count(&self) -> usize {
        self.nodes.iter().filter(|n| n.is_good()).count()
    }

    // -----------------------------------------------------------------------
    // Range checks
    // -----------------------------------------------------------------------

    /// Returns `true` if `node_id` falls within this bucket's [min, max] range.
    ///
    /// Uses lexicographic comparison, equivalent to C++ `isInRange()`.
    pub fn is_in_range(&self, node_id: &[u8; 20]) -> bool {
        node_id.as_slice() >= self.min_id.as_slice() && node_id.as_slice() <= self.max_id.as_slice()
    }

    // -----------------------------------------------------------------------
    // Node management
    // -----------------------------------------------------------------------

    /// Try to add a node to this bucket.
    ///
    /// - If the node's ID already exists, update it (move to tail).
    /// - If there's room, add the node.
    /// - If the bucket is full and the LRU node is bad, replace it with a
    ///   verified good candidate.
    /// - Otherwise, return `false` (bucket is full of good/questionable nodes).
    ///
    /// Equivalent to C++ `DHTBucket::addNode()`.
    pub fn add_node(&mut self, node: DhtNode) -> bool {
        self.try_add_node(node).is_ok()
    }

    /// Add a node while returning ownership when this full bucket cannot
    /// accept it, so the routing table can split the bucket or cache it.
    pub(super) fn try_add_node(&mut self, node: DhtNode) -> Result<(), DhtNode> {
        self.notify_update();

        // Check if the node already exists.
        if let Some(pos) = self.nodes.iter().position(|n| n.id == node.id) {
            // Update existing: remove old and add to tail (most recently seen).
            self.nodes.remove(pos);
            self.nodes.push(node);
            return Ok(());
        }

        if self.nodes.len() < K {
            self.nodes.push(node);
            return Ok(());
        }

        // Bucket is full. Try to replace a bad node (LRU = front).
        if let Some(front) = self.nodes.first()
            && front.is_bad()
            && node.is_good()
        {
            self.nodes.remove(0);
            self.nodes.push(node);
            return Ok(());
        }

        Err(node)
    }

    /// Cache a node for potential future replacement.
    ///
    /// Cached nodes are sorted by last-seen time (most recent at front).
    /// The cache is limited to `CACHE_SIZE` entries.
    ///
    /// Equivalent to C++ `DHTBucket::cacheNode()`.
    pub fn cache_node(&mut self, node: DhtNode) {
        self.cached_nodes.insert(0, node);
        if self.cached_nodes.len() > CACHE_SIZE {
            self.cached_nodes.truncate(CACHE_SIZE);
        }
    }

    /// Drop a node from the bucket, promoting the first cached node if available.
    ///
    /// Equivalent to C++ `DHTBucket::dropNode()`.
    /// Returns `true` if a node was removed.
    pub fn drop_node(&mut self, node_id: &[u8; 20]) -> bool {
        if let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) {
            self.nodes.remove(pos);
            // Promote the first cached node if available.
            if !self.cached_nodes.is_empty() {
                let replacement = self.cached_nodes.remove(0);
                self.nodes.push(replacement);
            }
            true
        } else {
            false
        }
    }

    /// Remove a node from the bucket (no replacement promotion).
    pub fn remove_node(&mut self, node_id: &[u8; 20]) -> bool {
        if let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) {
            self.nodes.remove(pos);
            true
        } else {
            false
        }
    }

    /// Replace a specific node with a candidate from this bucket.
    pub fn replace_node(&mut self, node_id: &[u8; 20], replacement: DhtNode) -> bool {
        if let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) {
            self.nodes.remove(pos);
            self.nodes.push(replacement);
            true
        } else {
            false
        }
    }

    /// Remove a replacement candidate by ID.
    pub fn remove_cached_node(&mut self, node_id: &[u8; 20]) -> bool {
        if let Some(pos) = self
            .cached_nodes
            .iter()
            .position(|node| &node.id == node_id)
        {
            self.cached_nodes.remove(pos);
            true
        } else {
            false
        }
    }

    /// Move a node to the head (front / LRU position) of the bucket.
    ///
    /// Equivalent to C++ `DHTBucket::moveToHead()`.
    pub fn move_to_head(&mut self, node_id: &[u8; 20]) {
        if let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) {
            let node = self.nodes.remove(pos);
            self.nodes.insert(0, node);
        }
    }

    /// Move a node to the tail (MRU position) of the bucket.
    ///
    /// Equivalent to C++ `DHTBucket::moveToTail()`.
    pub fn move_to_tail(&mut self, node_id: &[u8; 20]) {
        if let Some(pos) = self.nodes.iter().position(|n| &n.id == node_id) {
            let node = self.nodes.remove(pos);
            self.nodes.push(node);
        }
    }

    // -----------------------------------------------------------------------
    // Splitting
    // -----------------------------------------------------------------------

    /// Returns `true` if this bucket is allowed to be split.
    ///
    /// A bucket can be split if:
    /// 1. Its prefix length is less than 159 (cannot split beyond max depth).
    /// 2. The local node's ID falls within this bucket's range.
    ///
    /// Equivalent to C++ `DHTBucket::splitAllowed()`.
    pub fn split_allowed(&self) -> bool {
        self.prefix_length < ID_LENGTH * 8 - 1 && self.is_in_range(&self.local_id)
    }

    /// Split this bucket into two halves.
    ///
    /// This method mutates `self` to become the left half and returns the new
    /// right bucket. The split is done by flipping the bit at `prefix_length`:
    /// - Left half: IDs where the bit at `prefix_length` matches `min_id`
    /// - Right half: IDs where the bit at `prefix_length` is flipped
    ///
    /// After splitting, both buckets have `prefix_length + 1`.
    /// Nodes are redistributed to the appropriate half.
    ///
    /// Equivalent to C++ `DHTBucket::split()`.
    pub fn split(&mut self) -> Bucket {
        assert!(
            self.split_allowed(),
            "split() called on non-splittable bucket"
        );

        // Right bucket's max = current max.
        let r_max = self.max_id;

        // Right bucket's min = current min with bit at prefix_length flipped.
        let mut r_min = self.min_id;
        flip_bit(&mut r_min, self.prefix_length);

        // Left bucket's max = current max with bit at prefix_length flipped.
        flip_bit(&mut self.max_id, self.prefix_length);

        // Increment prefix length.
        self.prefix_length += 1;
        let new_prefix_length = self.prefix_length;

        // Create the right bucket.
        let mut right_bucket =
            Bucket::new_for_range(new_prefix_length, r_min, r_max, self.local_id);

        // Redistribute nodes.
        let mut remaining = Vec::with_capacity(K);
        for node in self.nodes.drain(..) {
            if right_bucket.is_in_range(&node.id) {
                right_bucket.nodes.push(node);
            } else {
                remaining.push(node);
            }
        }
        self.nodes = remaining;

        tracing::debug!(
            "Bucket split: left prefix={} range={}-{}, right prefix={} range={}-{}",
            self.prefix_length,
            hex::encode(self.min_id),
            hex::encode(self.max_id),
            right_bucket.prefix_length,
            hex::encode(right_bucket.min_id),
            hex::encode(right_bucket.max_id),
        );

        right_bucket
    }

    // -----------------------------------------------------------------------
    // Query helpers
    // -----------------------------------------------------------------------

    /// Returns `true` if this bucket needs a refresh.
    ///
    /// A bucket needs refresh if it has fewer than K nodes or hasn't been
    /// updated in `BUCKET_REFRESH_INTERVAL`.
    pub fn needs_refresh(&self) -> bool {
        self.nodes.len() < K
            || self.last_updated.elapsed().as_secs() >= BUCKET_REFRESH_INTERVAL_SECS
    }

    /// Returns `true` if this bucket contains at least one questionable node.
    pub fn contains_questionable_node(&self) -> bool {
        self.nodes.iter().any(|n| n.is_questionable())
    }

    /// Returns the LRU (least recently used) questionable node, if any.
    ///
    /// Equivalent to C++ `DHTBucket::getLRUQuestionableNode()`.
    pub fn get_lru_questionable_node(&self) -> Option<&DhtNode> {
        self.nodes.iter().find(|n| n.is_questionable())
    }

    /// Get a specific node by ID, IP address, and port.
    ///
    /// Equivalent to C++ `DHTBucket::getNode()`.
    pub fn get_node(&self, node_id: &[u8; 20], ip_addr: &str, port: u16) -> Option<&DhtNode> {
        self.nodes.iter().find(|n| {
            &n.id == node_id && n.addr.ip().to_string() == ip_addr && n.addr.port() == port
        })
    }

    /// Generate a random node ID that falls within this bucket's range.
    ///
    /// Equivalent to C++ `DHTBucket::getRandomNodeID()`.
    pub fn get_random_node_id(&self) -> [u8; 20] {
        use rand::Rng;
        let mut id = [0u8; 20];
        let mut rng = rand::thread_rng();

        if self.prefix_length == 0 {
            // Full range — generate completely random.
            rng.fill(&mut id);
        } else {
            // Copy the fixed prefix from min_id, randomize the rest.
            let last_byte_index = (self.prefix_length - 1) / 8;
            rng.fill(&mut id);
            // Overwrite the prefix portion.
            id[..=last_byte_index].copy_from_slice(&self.min_id[..=last_byte_index]);
        }

        id
    }

    /// Mark a node as good (reset failure count and update last_seen).
    pub fn mark_good(&mut self, node_id: &[u8; 20]) -> bool {
        if let Some(node) = self.nodes.iter_mut().find(|n| &n.id == node_id) {
            node.touch();
            true
        } else {
            false
        }
    }

    /// Mark a node as bad (increment failure count).
    pub fn mark_bad(&mut self, node_id: &[u8; 20]) -> bool {
        if let Some(node) = self.nodes.iter_mut().find(|n| &n.id == node_id) {
            node.record_failure();
            true
        } else {
            false
        }
    }

    /// Evict all bad nodes from this bucket.
    ///
    /// Returns the number of nodes evicted.
    pub fn evict_bad(&mut self) -> usize {
        let bad_node_ids = self
            .nodes
            .iter()
            .filter(|node| node.is_bad())
            .map(|node| node.id)
            .collect::<Vec<_>>();

        for node_id in &bad_node_ids {
            self.drop_node(node_id);
        }

        bad_node_ids.len()
    }

    /// Update the last-updated timestamp.
    fn notify_update(&mut self) {
        self.last_updated = Instant::now();
    }

    /// Collect recently verified good nodes from this bucket.
    pub fn get_good_nodes(&self) -> Vec<DhtNode> {
        self.nodes.iter().filter(|n| n.is_good()).cloned().collect()
    }

    /// Count questionable nodes in this bucket.
    pub fn questionable_count(&self) -> usize {
        self.nodes.iter().filter(|n| n.is_questionable()).count()
    }

    /// Count bad nodes in this bucket.
    pub fn bad_count(&self) -> usize {
        self.nodes.iter().filter(|n| n.is_bad()).count()
    }
}

impl Clone for Bucket {
    fn clone(&self) -> Self {
        Self {
            prefix_length: self.prefix_length,
            min_id: self.min_id,
            max_id: self.max_id,
            local_id: self.local_id,
            nodes: self.nodes.clone(),
            cached_nodes: self.cached_nodes.clone(),
            last_updated: self.last_updated,
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests;