aria2-core 0.3.14

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
//! WebSocket tracker announces used during magnet metadata discovery.
//!
//! WebTorrent-compatible trackers accept a JSON announce message over `ws` or
//! `wss`.  They are useful for magnet links that publish WebSocket trackers,
//! but their WebRTC-only offers cannot be consumed by aria2's TCP metadata
//! exchange.  This module therefore returns only TCP-compatible peers and
//! lets the normal DHT/HTTP/UDP fallbacks continue when a tracker has no such
//! peers.

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

use tokio::net::TcpStream;
use tracing::debug;

use crate::engine::bittorrent::tracker::communication::AnnounceEvent;
use crate::http::client_identity::ClientTlsConfig;
use crate::http::socks_connector::NoProxyMatcher;
use crate::http::{HttpConnectProxyTunnel, HttpProxyConfig, ProxyType};
use crate::network::OutboundNetworkPolicy;
use crate::request::request_group::DownloadOptions;
use aria2_protocol::bittorrent::tracker::public_list::TrackerFailureKind;
use aria2_protocol::bittorrent::tracker::websocket::{
    WebSocketAnnounceError, WebSocketAnnounceRequest, announce_over_stream_with_connector,
    parse_tracker_url,
};

/// Announce a magnet lookup to a WebSocket tracker.
///
/// The returned list contains only peers that can be represented as TCP
/// socket addresses.  WebTorrent trackers may return WebRTC `offers` instead;
/// those are intentionally ignored because the BitTorrent peer layer does
/// not implement WebRTC transport.
pub(crate) struct AnnounceRequest<'a> {
    pub(crate) info_hash: &'a [u8; 20],
    pub(crate) peer_id: &'a [u8; 20],
    pub(crate) downloaded: u64,
    pub(crate) left: u64,
    pub(crate) uploaded: u64,
    pub(crate) numwant: u32,
    pub(crate) port: u16,
    pub(crate) event: AnnounceEvent,
    pub(crate) request_timeout: Duration,
    pub(crate) connect_timeout: Duration,
    pub(crate) options: &'a DownloadOptions,
}

pub(crate) struct AnnounceResponse {
    pub(crate) peers: Vec<SocketAddr>,
    pub(crate) interval: Option<u64>,
    pub(crate) min_interval: Option<u64>,
    pub(crate) seeders: Option<i64>,
    pub(crate) leechers: Option<i64>,
}

#[derive(Debug)]
pub(crate) struct AnnounceError {
    pub(crate) kind: TrackerFailureKind,
    message: String,
}

impl AnnounceError {
    fn new(kind: TrackerFailureKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }
}

impl std::fmt::Display for AnnounceError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

pub(crate) async fn announce_with_policy(
    tracker_url: &str,
    announce: AnnounceRequest<'_>,
    policy: &OutboundNetworkPolicy,
    resolver: Option<&crate::dns::DnsResolver>,
) -> Result<AnnounceResponse, AnnounceError> {
    let url = parse_tracker_url(tracker_url).map_err(classify_websocket_announce_error)?;
    let host = url.host_str().ok_or_else(|| {
        AnnounceError::new(
            TrackerFailureKind::Network,
            "WebSocket tracker URL has no host",
        )
    })?;
    let port = url.port_or_known_default().ok_or_else(|| {
        AnnounceError::new(
            TrackerFailureKind::Network,
            "WebSocket tracker URL has no port",
        )
    })?;
    let connect_timeout = announce.connect_timeout.max(Duration::from_secs(1));
    let request_timeout = announce.request_timeout.max(Duration::from_secs(1));
    let connector = if url.scheme() == "wss" {
        Some(
            ClientTlsConfig::from_download_options(announce.options)
                .websocket_connector()
                .map_err(|error| {
                    AnnounceError::new(TrackerFailureKind::Network, error.to_string())
                })?,
        )
    } else {
        None
    };

    let stream = connect_socket(
        &url,
        host,
        port,
        announce.options,
        connect_timeout,
        policy,
        resolver,
    )
    .await?;
    let event = announce.event.as_event_string();
    let response = announce_over_stream_with_connector(
        stream,
        url.as_str(),
        &WebSocketAnnounceRequest {
            info_hash: announce.info_hash,
            peer_id: announce.peer_id,
            downloaded: announce.downloaded,
            left: announce.left,
            uploaded: announce.uploaded,
            numwant: announce.numwant,
            port: announce.port,
            event: Some(event),
        },
        request_timeout,
        connector,
    )
    .await
    .map_err(classify_websocket_announce_error)?;
    debug!(
        tracker = %aria2_protocol::http::redirect::url_origin_for_logging(tracker_url),
        peers = response.peers.len(),
        "WebSocket tracker announce completed"
    );
    Ok(AnnounceResponse {
        peers: response.peers,
        interval: response.interval,
        min_interval: response.min_interval,
        seeders: response.seeders,
        leechers: response.leechers,
    })
}

fn classify_websocket_announce_error(error: WebSocketAnnounceError) -> AnnounceError {
    let kind = match &error {
        WebSocketAnnounceError::Timeout(_) => TrackerFailureKind::Timeout,
        WebSocketAnnounceError::HandshakeRejected(status)
            if *status >= 500 || matches!(*status, 408 | 425 | 429) =>
        {
            TrackerFailureKind::RemoteTemporary
        }
        WebSocketAnnounceError::HandshakeRejected(_) => TrackerFailureKind::TrackerRejected,
        WebSocketAnnounceError::Protocol(_)
        | WebSocketAnnounceError::Response(
            aria2_protocol::bittorrent::tracker::websocket::WebSocketAnnounceResponseError::Malformed(_),
        ) => TrackerFailureKind::MalformedResponse,
        WebSocketAnnounceError::Response(
            aria2_protocol::bittorrent::tracker::websocket::WebSocketAnnounceResponseError::Rejected(_),
        ) => TrackerFailureKind::TrackerRejected,
        WebSocketAnnounceError::Closed
        | WebSocketAnnounceError::InvalidRequest(_)
        | WebSocketAnnounceError::Transport(_) => TrackerFailureKind::Network,
    };
    AnnounceError::new(kind, error.to_string())
}

async fn connect_socket(
    url: &url::Url,
    target_host: &str,
    target_port: u16,
    options: &DownloadOptions,
    timeout: Duration,
    policy: &OutboundNetworkPolicy,
    resolver: Option<&crate::dns::DnsResolver>,
) -> Result<TcpStream, AnnounceError> {
    let no_proxy = options
        .no_proxy
        .as_deref()
        .map(NoProxyMatcher::from_env_value)
        .is_some_and(|matcher| matcher.should_bypass_hostname(target_host));

    let proxy = if no_proxy {
        None
    } else if url.scheme() == "ws" {
        options
            .http_proxy
            .as_deref()
            .filter(|proxy| !proxy.is_empty())
            .or_else(|| {
                options
                    .all_proxy
                    .as_deref()
                    .filter(|proxy| !proxy.is_empty())
            })
    } else {
        options
            .https_proxy
            .as_deref()
            .filter(|proxy| !proxy.is_empty())
            .or_else(|| {
                options
                    .all_proxy
                    .as_deref()
                    .filter(|proxy| !proxy.is_empty())
            })
    };

    let Some(proxy_url) = proxy else {
        let connection = async {
            if let Some(resolver) = resolver {
                let addresses = resolver
                    .resolve(target_host, target_port)
                    .await
                    .map_err(|error| std::io::Error::other(error.to_string()))?;
                policy.connect_candidates(&addresses).await
            } else {
                policy.connect_host(target_host, target_port).await
            }
        };
        return tokio::time::timeout(timeout, connection)
            .await
            .map_err(|_| {
                AnnounceError::new(
                    TrackerFailureKind::Timeout,
                    "WebSocket tracker TCP connection timed out",
                )
            })?
            .map_err(|error| {
                AnnounceError::new(
                    TrackerFailureKind::Network,
                    format!("WebSocket tracker TCP connection failed: {error}"),
                )
            });
    };

    let credentials_selector = if url.scheme() == "ws" {
        "http"
    } else {
        "https"
    };
    let credentials = if (url.scheme() == "ws" && options.http_proxy.as_deref() == Some(proxy_url))
        || (url.scheme() == "wss" && options.https_proxy.as_deref() == Some(proxy_url))
    {
        options.proxy_credentials_for_scheme(credentials_selector)
    } else {
        options.proxy_credentials_for_scheme("all")
    };
    let mut config =
        HttpProxyConfig::from_proxy_url(proxy_url, target_host.to_string(), target_port).map_err(
            |error| {
                AnnounceError::new(
                    TrackerFailureKind::Network,
                    format!("invalid WebSocket proxy configuration: {error}"),
                )
            },
        )?;
    if config.proxy_type != ProxyType::Http {
        return Err(AnnounceError::new(
            TrackerFailureKind::Network,
            format!(
                "WebSocket tracker proxy must use an HTTP CONNECT proxy; '{}' is {}",
                proxy_url, config.proxy_type
            ),
        ));
    }
    if let Some(username) = credentials.0 {
        config = config.with_credentials(username, credentials.1.unwrap_or_default());
    }
    config.connect_timeout = timeout;
    config.read_timeout = timeout;
    config.write_timeout = timeout;

    tokio::time::timeout(
        timeout,
        HttpConnectProxyTunnel::new(config).connect_with_policy(policy),
    )
    .await
    .map_err(|_| {
        AnnounceError::new(
            TrackerFailureKind::Timeout,
            "WebSocket tracker proxy connection timed out",
        )
    })?
    .map_err(|error| {
        AnnounceError::new(
            TrackerFailureKind::Network,
            format!("WebSocket tracker proxy connection failed: {error}"),
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use aria2_protocol::bittorrent::tracker::websocket::decode_announce_response;
    use base64::Engine;
    use futures::{SinkExt, StreamExt};
    use serde_json::Value;
    use tokio_tungstenite::tungstenite::Message;

    #[test]
    fn classifies_close_without_response_as_transport_failure() {
        let error = classify_websocket_announce_error(WebSocketAnnounceError::Closed);

        assert_eq!(error.kind, TrackerFailureKind::Network);
    }

    #[test]
    fn parses_json_and_compact_peers() {
        let compact = base64::engine::general_purpose::STANDARD.encode([192, 0, 2, 1, 0x1a, 0xe1]);
        let value = serde_json::json!({
            "action": "announce",
            "peers": [
                {"ip": "192.0.2.2", "port": 6882},
                compact,
            ]
        });
        let encoded = value.to_string();
        let peers = decode_announce_response(&encoded).unwrap().peers;
        assert_eq!(
            peers,
            vec![
                "192.0.2.1:6881".parse().unwrap(),
                "192.0.2.2:6882".parse().unwrap(),
            ]
        );
    }

    #[tokio::test]
    async fn no_proxy_routes_websocket_tracker_directly() {
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let proxy_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let proxy_address = proxy_listener.local_addr().unwrap();
        let (proxy_connected_sender, mut proxy_connected_receiver) =
            tokio::sync::oneshot::channel();
        let proxy_task = tokio::spawn(async move {
            let _ = proxy_listener.accept().await;
            let _ = proxy_connected_sender.send(());
        });
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut websocket = tokio_tungstenite::accept_async(stream).await.unwrap();
            let Some(Ok(Message::Text(request))) = websocket.next().await else {
                panic!("tracker did not receive an announce")
            };
            let request: Value = serde_json::from_str(&request).unwrap();
            assert_eq!(request["action"], "announce");
            assert_eq!(
                request["info_hash"]
                    .as_str()
                    .unwrap()
                    .chars()
                    .map(u32::from)
                    .collect::<Vec<_>>(),
                vec![1; 20]
            );
            assert_eq!(
                request["peer_id"]
                    .as_str()
                    .unwrap()
                    .chars()
                    .map(u32::from)
                    .collect::<Vec<_>>(),
                vec![2; 20]
            );
            let response_info_hash = [1u8; 20]
                .iter()
                .copied()
                .map(char::from)
                .collect::<String>();
            websocket
                .send(Message::Text(
                    serde_json::json!({
                        "action": "announce",
                        "info_hash": response_info_hash,
                        "peers": [{"ip": "192.0.2.10", "port": 6881}]
                    })
                    .to_string()
                    .into(),
                ))
                .await
                .unwrap();
        });

        let options = DownloadOptions {
            http_proxy: Some(format!("http://{proxy_address}")),
            no_proxy: Some("127.0.0.1".to_string()),
            ca_certificate: Some("missing-ca-is-unused-for-ws.pem".to_string()),
            ..DownloadOptions::default()
        };
        let peers = announce_with_policy(
            &format!("ws://{address}/announce"),
            AnnounceRequest {
                info_hash: &[1u8; 20],
                peer_id: &[2u8; 20],
                downloaded: 0,
                left: 1,
                uploaded: 0,
                numwant: 50,
                port: 0,
                event: AnnounceEvent::Started,
                request_timeout: Duration::from_secs(5),
                connect_timeout: Duration::from_secs(5),
                options: &options,
            },
            &OutboundNetworkPolicy::direct(),
            None,
        )
        .await
        .unwrap();
        server.await.unwrap();
        assert!(matches!(
            proxy_connected_receiver.try_recv(),
            Err(tokio::sync::oneshot::error::TryRecvError::Empty)
        ));
        proxy_task.abort();
        let _ = proxy_task.await;
        assert_eq!(peers.peers, vec!["192.0.2.10:6881".parse().unwrap()]);
    }
}