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
//! Core DHT task implementations: PingTask, BucketRefreshTask, and bootstrap refresh.
//!
//! See `task_peer.rs` for peer-related tasks (PeerLookupTask and ReplaceNodeTask).

use std::sync::Arc;
use std::time::Duration;

use futures::StreamExt;
use tokio::sync::RwLock;
use tracing::{debug, info, trace, warn};

use super::lookup::iterative_find_node;
use super::message::DhtMessageBuilder;
use super::node::DhtNode;
use super::routing_table::RoutingTable;
use super::socket::DhtSocket;
use super::task::{DEFAULT_NUM_CONCURRENT, DhtTask};
use super::tracker::{QueryType, TransactionTracker};

const BUCKET_REFRESH_CONCURRENCY: usize = 3;

// ---------------------------------------------------------------------------
// Shared context for tasks that need engine resources
// ---------------------------------------------------------------------------

/// Shared context providing access to DHT engine resources.
///
/// In the C++ design, each `DHTAbstractTask` holds raw pointers to the
/// routing table, message dispatcher, message factory, and task queue.
/// In Rust, we bundle these behind `Arc<RwLock<>>` and `Arc<Mutex>` for
/// safe shared access across async tasks.
#[derive(Clone)]
pub struct DhtTaskContext {
    /// Local node ID.
    pub(crate) self_id: [u8; 20],
    /// Routing table (shared with the DHT engine).
    pub(crate) routing_table: Arc<RwLock<RoutingTable>>,
    /// UDP socket for sending messages.
    pub(crate) socket: DhtSocket,
    /// Transaction tracker for matching queries to responses.
    pub(crate) tracker: Arc<TransactionTracker>,
    /// Per-query timeout (C++ `DHT_MESSAGE_TIMEOUT = 10s`).
    pub(crate) query_timeout: Duration,
}

impl DhtTaskContext {
    pub fn new(
        self_id: [u8; 20],
        routing_table: Arc<RwLock<RoutingTable>>,
        socket: DhtSocket,
        tracker: Arc<TransactionTracker>,
        query_timeout: Duration,
    ) -> Self {
        Self {
            self_id,
            routing_table,
            socket,
            tracker,
            query_timeout,
        }
    }

    pub fn self_id(&self) -> &[u8; 20] {
        &self.self_id
    }

    pub fn routing_table(&self) -> &Arc<RwLock<RoutingTable>> {
        &self.routing_table
    }

    pub fn socket(&self) -> &DhtSocket {
        &self.socket
    }

    pub fn tracker(&self) -> &Arc<TransactionTracker> {
        &self.tracker
    }

    pub fn query_timeout(&self) -> Duration {
        self.query_timeout
    }
}

impl std::fmt::Debug for DhtTaskContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DhtTaskContext")
            .field("self_id", &hex::encode(self.self_id))
            .field("query_timeout", &self.query_timeout)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// PingTask
// ---------------------------------------------------------------------------

/// Send a ping to a remote node and wait for a response.
///
/// Equivalent to C++ `DHTPingTask`. If the node responds, it is marked
/// good in the routing table. Each unanswered attempt is recorded once.
#[derive(Debug)]
pub struct PingTask {
    ctx: DhtTaskContext,
    /// Remote node to ping.
    remote_node: DhtNode,
    /// Maximum retry count on timeout (C++ default: 0).
    max_retry: u32,
    /// Per-attempt timeout.
    timeout: Duration,
    /// Optional result channel used when discovering a node ID.
    result_tx: Option<tokio::sync::oneshot::Sender<Option<DhtNode>>>,
}

impl PingTask {
    /// Create a ping task, optionally returning the discovered node.
    pub fn new(
        ctx: DhtTaskContext,
        remote_node: DhtNode,
        max_retry: u32,
        result_tx: Option<tokio::sync::oneshot::Sender<Option<DhtNode>>>,
    ) -> Self {
        Self {
            timeout: ctx.query_timeout,
            ctx,
            remote_node,
            max_retry,
            result_tx,
        }
    }
}

#[async_trait::async_trait]
impl DhtTask for PingTask {
    async fn run(self: Box<Self>) {
        let addr = self.remote_node.addr;
        let node_id = self.remote_node.id;
        let mut result_tx = self.result_tx;

        for attempt in 0..=self.max_retry {
            if attempt > 0 {
                debug!(
                    attempt,
                    max_retry = self.max_retry,
                    "PingTask retrying node {}",
                    hex::encode(node_id),
                );
            }

            let (transaction_id, response_wait) =
                self.ctx
                    .tracker
                    .allocate_wait(QueryType::Ping, addr, self.timeout);
            let msg = DhtMessageBuilder::ping(transaction_id, &self.ctx.self_id);
            let encoded = msg.encode();

            if let Err(e) = self.ctx.socket.send_to(addr, &encoded).await {
                debug!("PingTask: send error to {}: {}", hex::encode(node_id), e);
                if let Some(tx) = result_tx.take() {
                    let _ = tx.send(None);
                }
                return;
            }

            if let Some(response) = response_wait.wait().await
                && response.from == addr
                && response.message.is_response()
            {
                let response_node = response
                    .message
                    .r
                    .as_ref()
                    .and_then(|result| result.dict_get(b"id"))
                    .and_then(|id| id.as_bytes())
                    .filter(|id| id.len() == 20)
                    .map(|id| {
                        let mut response_id = [0u8; 20];
                        response_id.copy_from_slice(id);
                        DhtNode::new(response_id, addr)
                    });

                if let Some(response_node) = response_node {
                    trace!(
                        "PingTask: node {} responded",
                        hex::encode(response_node.id())
                    );
                    let mut rt = self.ctx.routing_table.write().await;
                    if node_id != [0u8; 20] && node_id != *response_node.id() {
                        rt.remove(&node_id);
                    } else if node_id != [0u8; 20] {
                        rt.mark_good(&node_id);
                    }
                    rt.insert(response_node.clone());
                    if let Some(tx) = result_tx.take() {
                        let _ = tx.send(Some(response_node));
                    }
                    return;
                }
            }

            // The query owner accounts for this attempt. The engine timeout
            // loop only expires transactions and wakes us; it must not also
            // increment the same node's failure counter.
            let mut routing_table = self.ctx.routing_table.write().await;
            routing_table.mark_bad(&node_id);
            routing_table.evict_bad_nodes();
        }

        // All attempts exhausted without a valid response.
        debug!(
            "PingTask: node {} timed out after {} attempts",
            hex::encode(node_id),
            self.max_retry + 1
        );
        if let Some(tx) = result_tx {
            let _ = tx.send(None);
        }
    }

    fn name(&self) -> &'static str {
        "PingTask"
    }
}

// ---------------------------------------------------------------------------
// BucketRefreshTask
// ---------------------------------------------------------------------------

/// Refresh stale k-buckets by performing `find_node` lookups.
///
/// Equivalent to C++ `DHTBucketRefreshTask`. Iterates over all buckets
/// and issues a `find_node` lookup for a random ID in each bucket that
/// needs refreshing (fewer than K nodes or not updated in 15 minutes).
///
/// When `force_refresh` is true, all buckets are refreshed regardless of
/// their staleness. This is used during bootstrap.
#[derive(Debug)]
pub struct BucketRefreshTask {
    ctx: DhtTaskContext,
    /// If true, refresh all buckets regardless of staleness.
    force_refresh: bool,
}

impl BucketRefreshTask {
    /// Create a new bucket refresh task.
    pub fn new(ctx: DhtTaskContext, force_refresh: bool) -> Self {
        Self { ctx, force_refresh }
    }
}

#[async_trait::async_trait]
impl DhtTask for BucketRefreshTask {
    async fn run(self: Box<Self>) {
        let targets = {
            let rt = self.ctx.routing_table.read().await;
            if self.force_refresh {
                rt.get_all_buckets()
                    .iter()
                    .map(|b| b.get_random_node_id())
                    .collect::<Vec<_>>()
            } else {
                rt.refresh_buckets()
            }
        };

        if targets.is_empty() {
            trace!("BucketRefreshTask: no buckets need refresh");
            return;
        }

        info!(count = targets.len(), "Dispatching bucket refresh lookups");

        let ctx = &self.ctx;
        futures::stream::iter(targets)
            .map(|target| async move {
                let result = iterative_find_node(
                    &target,
                    &ctx.self_id,
                    &ctx.routing_table,
                    &ctx.socket,
                    &ctx.tracker,
                    ctx.query_timeout,
                )
                .await;
                (target, result)
            })
            .buffer_unordered(BUCKET_REFRESH_CONCURRENCY)
            .for_each(|(target, result)| async move {
                trace!(
                    target = %hex::encode(target),
                    nodes_contacted = result.nodes_contacted,
                    "Bucket refresh lookup completed"
                );
            })
            .await;
    }

    fn name(&self) -> &'static str {
        "BucketRefreshTask"
    }
}

/// Run the initial forced refresh with an explicit bootstrap deadline.
#[derive(Debug)]
pub(super) struct BootstrapRefreshTask {
    ctx: DhtTaskContext,
    timeout: Duration,
    bootstrap_nodes: Vec<DhtNode>,
    max_concurrent_pings: usize,
}

impl BootstrapRefreshTask {
    pub(super) fn new(
        ctx: DhtTaskContext,
        timeout: Duration,
        bootstrap_nodes: Vec<DhtNode>,
        max_concurrent_pings: usize,
    ) -> Self {
        Self {
            ctx,
            timeout,
            bootstrap_nodes,
            max_concurrent_pings: max_concurrent_pings.clamp(1, DEFAULT_NUM_CONCURRENT),
        }
    }
}

#[async_trait::async_trait]
impl DhtTask for BootstrapRefreshTask {
    async fn run(self: Box<Self>) {
        const BOOTSTRAP_PING_MAX_RETRIES: u32 = 9;

        let ctx = self.ctx;
        let bootstrap_nodes = self.bootstrap_nodes;
        let max_concurrent_pings = self.max_concurrent_pings;
        let refresh = async move {
            futures::stream::iter(bootstrap_nodes.into_iter().map(|node| {
                let ctx = ctx.clone();
                async move {
                    Box::new(PingTask::new(ctx, node, BOOTSTRAP_PING_MAX_RETRIES, None))
                        .run()
                        .await;
                }
            }))
            .buffer_unordered(max_concurrent_pings)
            .for_each(|_| async {})
            .await;

            Box::new(BucketRefreshTask::new(ctx, true)).run().await;
        };

        if tokio::time::timeout(self.timeout, refresh).await.is_err() {
            warn!(timeout = ?self.timeout, "DHT bootstrap refresh timed out");
        }
    }

    fn name(&self) -> &'static str {
        "BootstrapRefreshTask"
    }
}

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

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

    #[test]
    fn test_task_context_creation() {
        let ctx = DhtTaskContext::new(
            [0u8; 20],
            Arc::new(RwLock::new(RoutingTable::new([0u8; 20]))),
            DhtSocket::new_test(),
            Arc::new(TransactionTracker::new()),
            Duration::from_secs(10),
        );
        assert_eq!(ctx.self_id(), &[0u8; 20]);
        assert_eq!(ctx.query_timeout(), Duration::from_secs(10));
    }

    #[test]
    fn bootstrap_refresh_respects_configured_concurrency_with_safety_cap() {
        let context = || {
            DhtTaskContext::new(
                [0u8; 20],
                Arc::new(RwLock::new(RoutingTable::new([0u8; 20]))),
                DhtSocket::new_test(),
                Arc::new(TransactionTracker::new()),
                Duration::from_secs(10),
            )
        };

        for (configured, expected) in [(0, 1), (2, 2), (128, DEFAULT_NUM_CONCURRENT)] {
            let task = BootstrapRefreshTask::new(
                context(),
                Duration::from_secs(1),
                Vec::new(),
                configured,
            );

            assert_eq!(task.max_concurrent_pings, expected);
        }
    }
}