aria2-core 0.2.8

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
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
//! DHT message receiver for inbound messages.
//!
//! Receives raw UDP datagrams, decodes them into DHT message types,
//! and processes them by updating the routing table and dispatching
//! automatic responses (e.g., ping replies, find_node replies).
//!
//! C++ reference: `DHTMessageReceiver.h/cc`

use std::net::SocketAddr;
use std::time::Duration;

use tracing::{debug, trace, warn};

use super::dispatcher::DhtDispatcher;
use super::message::DhtMessage;
use super::message_decode;
use super::node::DhtNode;
use super::node_id::NodeId;
use super::peer_announce::DhtPeerAnnounceStorage;
use super::routing_table::RoutingTable;
use super::token_tracker::TokenTracker;

// ── ReceiveAction ─────────────────────────────────────────────────────────

/// Result of processing a received DHT message.
#[derive(Debug)]
pub enum ReceiveAction {
    /// The message was an inbound query; a response should be sent.
    Respond(DhtMessage),
    /// The message was an inbound response; the routing table was updated.
    ResponseReceived {
        method: String,
        sender_addr: SocketAddr,
        /// The target node ID from the tracked query (used for node ID change detection).
        /// C++: `DHTMessageTracker::messageArrived()` compares `targetNode`
        /// against `message->getRemoteNode()` and drops stale entries.
        target_node_id: NodeId,
        /// Elapsed time since the query was dispatched (for RTT update).
        /// C++: `node->updateRTT(rtt)` in `DHTMessageTracker::messageArrived()`.
        elapsed: Duration,
    },
    /// The message was an error or unknown; no action needed.
    NoAction,
}

// ── DhtReceiver ───────────────────────────────────────────────────────────

/// Receives and processes inbound DHT messages.
///
/// The receiver decodes raw UDP datagrams into [`DhtMessage`] values and
/// handles them according to their type:
///
/// - **Queries**: Update the routing table with the sender's node info,
///   then return a [`ReceiveAction::Respond`] with the appropriate reply.
/// - **Responses**: Match the response to a tracked outbound query via
///   the dispatcher's tracker, then update the routing table.
/// - **Errors**: Log and discard.
///
/// C++: `DHTMessageReceiver`
pub struct DhtReceiver {
    /// The local node's ID.
    local_id: NodeId,
}

impl DhtReceiver {
    /// Create a new receiver for the given local node ID.
    pub fn new(local_id: NodeId) -> Self {
        Self { local_id }
    }

    /// Process a received raw DHT datagram.
    ///
    /// Decodes the message, matches responses to tracked queries,
    /// and returns the appropriate action for the caller to take.
    pub fn receive_message(
        &self,
        data: &[u8],
        remote_addr: SocketAddr,
        dispatcher: &mut DhtDispatcher,
        routing_table: &mut RoutingTable,
        peer_announce_storage: &mut DhtPeerAnnounceStorage,
        token_tracker: &mut TokenTracker,
    ) -> Vec<ReceiveAction> {
        let mut actions = Vec::new();

        // Step 1: Is this a response to a tracked query?
        // Peek at the transaction ID first without decoding the full message.
        if let Some(tid) = Self::extract_transaction_id(data)
            && let Some(tracked) = dispatcher.take_tracked(&tid, remote_addr)
        {
            // This is a response to one of our queries
            let method = tracked.method.clone();
            let target_node_id = tracked.target_node_id;
            let elapsed = tracked.elapsed;
            trace!(
                tid = ?tid,
                addr = %remote_addr,
                method = %method,
                "Received DHT response matching tracked query"
            );

            // Decode the response using the known method
            match message_decode::decode_response_with_method(data, remote_addr, &method) {
                Ok(msg) => {
                    self.handle_response(
                        &msg,
                        remote_addr,
                        target_node_id,
                        elapsed,
                        routing_table,
                        peer_announce_storage,
                        &mut actions,
                    );
                }
                Err(e) => {
                    warn!(
                        addr = %remote_addr,
                        method = %method,
                        error = %e,
                        "Failed to decode DHT response"
                    );
                }
            }
            return actions;
        }

        // Step 2: Try to decode as a new query or error
        match message_decode::decode(data, remote_addr) {
            Ok(msg) => {
                self.handle_query(
                    &msg,
                    remote_addr,
                    routing_table,
                    peer_announce_storage,
                    token_tracker,
                    &mut actions,
                );
            }
            Err(e) => {
                // Could be a response with an unknown transaction ID,
                // or a malformed message.
                trace!(
                    addr = %remote_addr,
                    error = %e,
                    "Failed to decode DHT message (may be unknown response)"
                );
            }
        }

        actions
    }

    /// Handle a decoded response message.
    ///
    /// Performs node ID change detection (C++ `DHTMessageTracker::messageArrived()`)
    /// and RTT update (C++ `node->updateRTT()`).
    #[allow(clippy::too_many_arguments)]
    fn handle_response(
        &self,
        msg: &DhtMessage,
        _remote_addr: SocketAddr,
        target_node_id: NodeId,
        elapsed: Duration,
        routing_table: &mut RoutingTable,
        peer_announce_storage: &mut DhtPeerAnnounceStorage,
        actions: &mut Vec<ReceiveAction>,
    ) {
        // C++: DHTMessageTracker::messageArrived() compares targetNode's ID
        // with the response's sender ID. If they differ, the old node is
        // dropped from the routing table because its identity has changed.
        if let Some(sender_id) = msg.sender_id() {
            if *sender_id != target_node_id && target_node_id != NodeId::ZERO {
                debug!(
                    old_id = %target_node_id,
                    new_id = %sender_id,
                    "Node ID has changed, dropping stale entry from routing table"
                );
                routing_table.drop_node(&target_node_id);
            }

            // Add the responding node to the routing table as a "good" node
            // since it just responded successfully.
            let mut node = DhtNode::new(*sender_id, *msg.sender_addr());
            node.update_rtt(elapsed.as_millis() as u64);
            routing_table.add_good_node(node);
        }

        // Handle get_peers responses: store discovered peers
        if let DhtMessage::GetPeersResponse { payload, .. } = msg {
            for peer_info in &payload.values {
                peer_announce_storage.add_peer_announce(
                    // We don't know the info hash from the response alone,
                    // but the task system does. For now, just add the peer.
                    // This will be properly wired via the task callback.
                    &NodeId::ZERO, // placeholder
                    peer_info.addr,
                );
            }
        }

        actions.push(ReceiveAction::ResponseReceived {
            method: msg.method_name().unwrap_or("unknown").to_owned(),
            sender_addr: *msg.sender_addr(),
            target_node_id,
            elapsed,
        });
    }

    /// Handle a decoded query message.
    fn handle_query(
        &self,
        msg: &DhtMessage,
        remote_addr: SocketAddr,
        routing_table: &mut RoutingTable,
        peer_announce_storage: &mut DhtPeerAnnounceStorage,
        token_tracker: &mut TokenTracker,
        actions: &mut Vec<ReceiveAction>,
    ) {
        // Add the querying node to the routing table
        if let Some(sender_id) = msg.sender_id() {
            let node = DhtNode::new(*sender_id, remote_addr);
            routing_table.add_node(node);
        }

        // Generate the appropriate response
        match msg {
            DhtMessage::PingQuery { transaction_id, .. } => {
                debug!(tid = ?transaction_id, addr = %remote_addr, "Received DHT ping query");
                let reply = DhtMessage::PingResponse {
                    transaction_id: transaction_id.clone(),
                    sender_id: self.local_id,
                    sender_addr: remote_addr,
                    payload: super::message::PingResponsePayload,
                };
                actions.push(ReceiveAction::Respond(reply));
            }

            DhtMessage::FindNodeQuery {
                transaction_id,
                sender_id: _,
                payload,
                ..
            } => {
                debug!(
                    tid = ?transaction_id,
                    addr = %remote_addr,
                    target = %payload.target,
                    "Received DHT find_node query"
                );
                let closest = routing_table.get_closest_k_nodes(&payload.target);
                let nodes: Vec<super::message::CompactNodeInfo> = closest
                    .into_iter()
                    .map(|n| super::message::CompactNodeInfo {
                        node_id: *n.id(),
                        addr: n.addr(),
                    })
                    .collect();

                let reply = DhtMessage::FindNodeResponse {
                    transaction_id: transaction_id.clone(),
                    sender_id: self.local_id,
                    sender_addr: remote_addr,
                    payload: super::message::FindNodeResponsePayload { nodes },
                };
                actions.push(ReceiveAction::Respond(reply));
            }

            DhtMessage::GetPeersQuery {
                transaction_id,
                sender_id: _,
                payload,
                ..
            } => {
                debug!(
                    tid = ?transaction_id,
                    addr = %remote_addr,
                    info_hash = %payload.info_hash,
                    "Received DHT get_peers query"
                );

                // Generate a token for this IP and port
                let ip_str = remote_addr.ip().to_string();
                let port = remote_addr.port();
                let token =
                    token_tracker.generate_token(payload.info_hash.as_bytes(), &ip_str, port);

                // Check if we have peers for this info hash
                let peers = peer_announce_storage.get_peers(&payload.info_hash);
                let values: Vec<super::message::CompactPeerInfo> = peers
                    .into_iter()
                    .map(|addr| super::message::CompactPeerInfo { addr })
                    .collect();

                // Also return closest nodes
                let closest = routing_table.get_closest_k_nodes(&payload.info_hash);
                let nodes: Vec<super::message::CompactNodeInfo> = closest
                    .into_iter()
                    .map(|n| super::message::CompactNodeInfo {
                        node_id: *n.id(),
                        addr: n.addr(),
                    })
                    .collect();

                let reply = DhtMessage::GetPeersResponse {
                    transaction_id: transaction_id.clone(),
                    sender_id: self.local_id,
                    sender_addr: remote_addr,
                    payload: super::message::GetPeersResponsePayload {
                        token,
                        nodes,
                        values,
                    },
                };
                actions.push(ReceiveAction::Respond(reply));
            }

            DhtMessage::AnnouncePeerQuery {
                transaction_id,
                sender_id: _,
                payload,
                ..
            } => {
                debug!(
                    tid = ?transaction_id,
                    addr = %remote_addr,
                    info_hash = %payload.info_hash,
                    port = payload.port,
                    "Received DHT announce_peer query"
                );

                // Validate the token
                let ip_str = remote_addr.ip().to_string();
                let port = remote_addr.port();
                if token_tracker.validate_token(
                    &payload.token,
                    payload.info_hash.as_bytes(),
                    &ip_str,
                    port,
                ) {
                    // Store the announced peer
                    let announce_addr = if payload.port > 0 {
                        SocketAddr::new(remote_addr.ip(), payload.port)
                    } else {
                        remote_addr
                    };
                    peer_announce_storage.add_peer_announce(&payload.info_hash, announce_addr);

                    let reply = DhtMessage::AnnouncePeerResponse {
                        transaction_id: transaction_id.clone(),
                        sender_id: self.local_id,
                        sender_addr: remote_addr,
                        payload: super::message::AnnouncePeerResponsePayload,
                    };
                    actions.push(ReceiveAction::Respond(reply));
                } else {
                    warn!(
                        addr = %remote_addr,
                        "Invalid token in announce_peer query, ignoring"
                    );
                }
            }

            DhtMessage::Error { code, message, .. } => {
                warn!(
                    addr = %remote_addr,
                    code = code,
                    msg = %message,
                    "Received DHT error message"
                );
                actions.push(ReceiveAction::NoAction);
            }

            // Response messages should have been handled by handle_response
            _ => {
                trace!(addr = %remote_addr, "Unexpected message type in query handler");
            }
        }
    }

    /// Extract the transaction ID from a raw bencoded DHT message.
    ///
    /// Returns `None` if the message doesn't contain a "t" key or if
    /// parsing fails.
    fn extract_transaction_id(data: &[u8]) -> Option<Vec<u8>> {
        // Quick bencode parse: find "1:t" followed by the length and bytes
        // This is a fast path to avoid full decode for response matching.
        // The full decode happens later if we need to process the message.

        // Find "1:t" in the data
        let pattern = b"1:t";
        let start = data.windows(3).position(|w| w == pattern)?;

        // After "1:t", expect a bencode integer length (e.g., "4:") followed by bytes
        let after = &data[start + 3..];

        // Parse the length
        let colon_pos = after.iter().position(|&b| b == b':')?;
        let len_str = std::str::from_utf8(&after[..colon_pos]).ok()?;
        let len: usize = len_str.parse().ok()?;

        // Extract the bytes
        let tid_start = colon_pos + 1;
        let tid_end = tid_start + len;
        if tid_end > after.len() {
            return None;
        }
        Some(after[tid_start..tid_end].to_vec())
    }

    /// Handle message tracker timeouts.
    ///
    /// Called periodically to clean up unanswered queries. Updates node
    /// state in the routing table (RTT, timeout counter, bad node eviction),
    /// matching C++ `DHTMessageTracker::handleTimeoutEntry()` behavior.
    pub fn handle_timeouts(
        &self,
        dispatcher: &mut DhtDispatcher,
        routing_table: &mut RoutingTable,
    ) -> Vec<super::tracker::TimeoutEntry> {
        let timed_out = dispatcher.handle_timeouts();

        for entry in &timed_out {
            debug!(
                addr = %entry.target_addr,
                method = %entry.method,
                elapsed_ms = entry.elapsed.as_millis(),
                "DHT query timed out"
            );

            // C++: DHTMessageTracker::handleTimeoutEntry() calls
            // node->updateRTT(elapsed) and node->timeout().
            // If the node becomes bad, it will be evicted during bucket
            // refresh or when a replacement candidate is available.
            if entry.target_node_id != NodeId::ZERO {
                let node_id = entry.target_node_id;
                let rtt_ms = entry.elapsed.as_millis() as u64;

                // Update the node's RTT and increment timeout counter.
                // C++: DHTMessageTracker::handleTimeoutEntry():
                //   node->updateRTT(entry->getElapsed());
                //   node->timeout()  (increments condition counter)
                if let Some(node) = routing_table.get_node_mut(&node_id) {
                    node.update_rtt(rtt_ms);
                    node.timeout();
                    trace!(
                        node_id = %node_id,
                        rtt_ms = rtt_ms,
                        condition = node.condition(),
                        "Applied timeout penalty to DHT node"
                    );

                    // C++ does not immediately drop bad nodes on timeout.
                    // Instead, DHTReplaceNodeTask pings the LRU questionable
                    // node and replaces it if it doesn't respond. Bad nodes
                    // are also evicted when a new node is added to a full bucket.
                } else {
                    // Node may have already been dropped; just move to tail
                    // for any remaining reference.
                    routing_table.move_bucket_tail(&node_id);
                }
            }
        }

        timed_out
    }
}

// ── Unit tests ────────────────────────────────────────────────────────────

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

    fn test_local_id() -> NodeId {
        NodeId([0xAA; ID_LENGTH])
    }

    #[allow(dead_code)]
    fn test_addr() -> SocketAddr {
        "192.168.0.1:6881".parse().unwrap()
    }

    #[allow(dead_code)]
    fn test_sender_id() -> NodeId {
        NodeId([0xBB; ID_LENGTH])
    }

    #[test]
    fn extract_tid_from_ping_query() {
        // Minimal bencoded ping: d1:t4:abcd1:y1:q1:q4:pinge
        let data = b"d1:t4:abcd1:y1:q1:q4:pinge";
        let tid = DhtReceiver::extract_transaction_id(data);
        assert_eq!(tid, Some(b"abcd".to_vec()));
    }

    #[test]
    fn extract_tid_from_response() {
        // Minimal bencoded response: d1:t2:xx1:y1:re
        let data = b"d1:t2:xx1:y1:re";
        let tid = DhtReceiver::extract_transaction_id(data);
        assert_eq!(tid, Some(b"xx".to_vec()));
    }

    #[test]
    fn extract_tid_missing_returns_none() {
        let data = b"d1:y1:qe";
        let tid = DhtReceiver::extract_transaction_id(data);
        assert!(tid.is_none());
    }

    #[test]
    fn extract_tid_empty_data() {
        let tid = DhtReceiver::extract_transaction_id(b"");
        assert!(tid.is_none());
    }

    #[test]
    fn new_receiver_has_local_id() {
        let r = DhtReceiver::new(test_local_id());
        assert_eq!(r.local_id, test_local_id());
    }
}