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
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
524
525
//! FTP control connection establishment and data-channel TLS.

use std::sync::Arc;
use std::time::{Duration, Instant};

use tracing::{debug, info};

use crate::constants;
use crate::error::{Aria2Error, RecoverableError, Result};
use aria2_protocol::ftp::connection::{FtpControlSession, FtpControlSessionError};
use aria2_protocol::ftp::tls::{self as tls, FtpControlStream, FtpDataStream, FtpsClient};

use crate::ftp::connection::{FtpProxyConfig, FtpProxyTunnel, FtpProxyTunnelConfig};
use crate::ftp::connection_pool::PooledControlSession;
use crate::network::{ConnectionContext, OutboundNetworkPolicy};

// ---------------------------------------------------------------------------
// RawFtpControl
// ---------------------------------------------------------------------------

/// Raw FTP control connection handler
pub(super) struct RawFtpControl {
    pub(super) reader: FtpControlSession<FtpControlStream>,
    pub(super) host: String,
    pub(super) connection: ConnectionContext,
    pub(super) ftps_client: Option<FtpsClient>,
    pub(super) outbound_network_policy: Arc<OutboundNetworkPolicy>,
    request_timeout: Option<Duration>,
    pool_lifetime: (Instant, u64),
}

impl RawFtpControl {
    pub(super) fn from_pooled(session: PooledControlSession) -> Self {
        let (
            reader,
            connection,
            ftps_client,
            outbound_network_policy,
            created_at,
            _last_used,
            reuse_count,
        ) = session.into_parts();
        Self {
            reader,
            host: connection.endpoint.hostname().to_owned(),
            connection,
            ftps_client,
            outbound_network_policy,
            request_timeout: None,
            pool_lifetime: (created_at, reuse_count),
        }
    }

    pub(super) fn into_pooled(self) -> PooledControlSession {
        let (created_at, reuse_count) = self.pool_lifetime;
        let mut pooled = PooledControlSession::new(
            self.reader,
            self.connection,
            self.ftps_client,
            self.outbound_network_policy,
        );
        pooled.restore_lifetime(created_at, reuse_count);
        pooled
    }

    async fn connect_tcp_at(
        host: &str,
        port: u16,
        socket_addr: std::net::SocketAddr,
        outbound_network_policy: Arc<OutboundNetworkPolicy>,
    ) -> Result<(tokio::net::TcpStream, ConnectionContext)> {
        let addr = format!("{}:{}", host, port);
        debug!("Connecting to FTP server at {} via {}", addr, socket_addr);

        let stream = outbound_network_policy
            .connect(socket_addr)
            .await
            .map_err(|e| {
                Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                    message: format!("FTP connect failed to {}:{}: {}", host, port, e),
                })
            })?;
        let peer_addr = stream.peer_addr().map_err(|e| {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!("FTP peer address unavailable: {}", e),
            })
        })?;
        let connection = ConnectionContext::new(host, port, peer_addr);

        stream.set_nodelay(true).map_err(|e| {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!("set_nodelay failed: {}", e),
            })
        })?;

        Ok((stream, connection))
    }

    fn from_stream(
        stream: FtpControlStream,
        host: &str,
        connection: ConnectionContext,
        ftps_client: Option<FtpsClient>,
        outbound_network_policy: Arc<OutboundNetworkPolicy>,
    ) -> Self {
        Self {
            reader: FtpControlSession::new(stream),
            host: host.to_string(),
            connection,
            ftps_client,
            outbound_network_policy,
            request_timeout: None,
            pool_lifetime: (Instant::now(), 0),
        }
    }

    pub(super) fn set_request_timeout(&mut self, timeout: Option<Duration>) {
        self.request_timeout = timeout;
    }

    pub(super) fn command_timeout(&self) -> Duration {
        self.request_timeout
            .unwrap_or_else(|| Duration::from_secs(constants::FTP_COMMAND_TIMEOUT_SECS))
    }

    pub(super) fn data_connection_timeout(&self) -> Duration {
        self.request_timeout
            .unwrap_or_else(|| Duration::from_secs(constants::FTP_DATA_CONNECTION_TIMEOUT_SECS))
    }

    pub(super) fn transfer_completion_timeout(&self) -> Duration {
        self.request_timeout
            .unwrap_or_else(|| Duration::from_secs(constants::FTP_TRANSFER_COMPLETE_TIMEOUT_SECS))
    }

    async fn read_welcome(&mut self, request_timeout: Option<Duration>) -> Result<()> {
        let welcome = self
            .read_response(
                request_timeout
                    .unwrap_or_else(|| Duration::from_secs(constants::FTP_WELCOME_TIMEOUT_SECS)),
            )
            .await?;

        if welcome.0 != 220 {
            return Err(Aria2Error::Recoverable(
                RecoverableError::FtpProtocolError {
                    message: format!("FTP greeting rejected: {} {}", welcome.0, welcome.1),
                },
            ));
        }

        Ok(())
    }

    /// Send a command to the FTP server.
    #[cfg(test)]
    pub(super) async fn send_command(&mut self, cmd: &str) -> Result<()> {
        debug!(
            "FTP CMD: {}",
            cmd.split_whitespace().next().unwrap_or_default()
        );
        self.reader
            .send_command(cmd)
            .await
            .map_err(map_session_error)?;
        Ok(())
    }

    /// Read response from FTP server with timeout.
    pub(super) async fn read_response(&mut self, timeout_dur: Duration) -> Result<(u16, String)> {
        let response = self
            .reader
            .read_response(timeout_dur)
            .await
            .map_err(map_session_error)?;
        Ok((response.code, response.message))
    }

    pub(super) fn connection_context(&self) -> &ConnectionContext {
        &self.connection
    }

    pub(super) async fn secure_data_stream(
        &self,
        stream: tokio::net::TcpStream,
    ) -> Result<FtpDataStream> {
        if let Some(client) = &self.ftps_client {
            let tls_stream = client
                .upgrade_data_stream(stream, &self.host)
                .await
                .map_err(|error| {
                    Aria2Error::Network(format!("FTPS data TLS handshake failed: {}", error))
                })?;
            Ok(FtpDataStream::Tls(Box::new(tls_stream)))
        } else {
            Ok(FtpDataStream::Plain(stream))
        }
    }

    /// Send command and read response in one operation.
    #[cfg(test)]
    pub(super) async fn command(&mut self, cmd: &str) -> Result<(u16, String)> {
        self.send_command(cmd).await?;
        self.read_response(Duration::from_secs(constants::FTP_COMMAND_TIMEOUT_SECS))
            .await
    }

    pub(super) async fn connect_at(
        host: &str,
        port: u16,
        socket_addr: std::net::SocketAddr,
        outbound_network_policy: Arc<OutboundNetworkPolicy>,
        request_timeout: Option<Duration>,
    ) -> Result<Self> {
        let (stream, connection) = Self::connect_tcp_at(
            host,
            port,
            socket_addr,
            Arc::clone(&outbound_network_policy),
        )
        .await?;
        let mut ctrl = Self::from_stream(
            FtpControlStream::Plain(stream),
            host,
            connection,
            None,
            outbound_network_policy,
        );
        ctrl.read_welcome(request_timeout).await?;

        info!("Connected to FTP server {}:{}", host, port);
        Ok(ctrl)
    }

    /// Connect to an FTP server through an HTTP CONNECT proxy.
    ///
    /// The proxy connection is established before the FTP greeting is read,
    /// matching aria2's tunnel command chain while keeping the control state
    /// owned by this Rust command.
    pub(super) async fn connect_via_http_proxy(
        host: &str,
        port: u16,
        proxy: &FtpProxyConfig,
        ftps_client: Option<&FtpsClient>,
        ftps_implicit: bool,
        outbound_network_policy: Arc<OutboundNetworkPolicy>,
        request_timeout: Option<Duration>,
    ) -> Result<Self> {
        let tunnel_config = FtpProxyTunnelConfig {
            proxy_host: proxy.proxy_host.clone(),
            proxy_port: proxy.proxy_port,
            target_host: host.to_string(),
            target_port: port,
            proxy_username: proxy.proxy_username.clone(),
            proxy_password: proxy.proxy_password.clone(),
            connect_timeout: proxy.connect_timeout,
            read_timeout: proxy.connect_timeout,
            user_agent: proxy.user_agent.clone(),
        };
        let stream =
            FtpProxyTunnel::establish_with_policy(&tunnel_config, &outbound_network_policy).await?;
        let peer_addr = stream.peer_addr().map_err(|error| {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!("FTP proxy peer address unavailable: {}", error),
            })
        })?;
        let connection = ConnectionContext::new(host, port, peer_addr);

        if let Some(client) = ftps_client {
            if ftps_implicit {
                let tls_stream =
                    client
                        .perform_tls_handshake(stream, host)
                        .await
                        .map_err(|error| {
                            Aria2Error::Network(format!(
                                "FTPS proxy TLS handshake failed: {}",
                                error
                            ))
                        })?;
                let mut ctrl = Self::from_stream(
                    FtpControlStream::Tls(Box::new(tls_stream)),
                    host,
                    connection,
                    Some(client.clone()),
                    Arc::clone(&outbound_network_policy),
                );
                ctrl.read_welcome(request_timeout).await?;
                tls::negotiate_protected_data_channel(ctrl.reader.reader_mut())
                    .await
                    .map_err(|error| {
                        Aria2Error::Network(format!("FTPS data protection failed: {}", error))
                    })?;
                return Ok(ctrl);
            }

            let mut plain = Self::from_stream(
                FtpControlStream::Plain(stream),
                host,
                connection.clone(),
                None,
                Arc::clone(&outbound_network_policy),
            );
            plain.read_welcome(request_timeout).await?;
            let Self {
                reader,
                host,
                connection,
                ..
            } = plain;
            let stream = match reader.into_inner() {
                FtpControlStream::Plain(stream) => stream,
                FtpControlStream::Tls(_) => unreachable!("fresh FTPS proxy stream is plain"),
            };
            let tls_stream =
                client
                    .upgrade_control_stream(stream, &host)
                    .await
                    .map_err(|error| {
                        Aria2Error::Network(format!("FTPS proxy control upgrade failed: {}", error))
                    })?;
            let mut ctrl = Self::from_stream(
                FtpControlStream::Tls(Box::new(tls_stream)),
                &host,
                connection,
                Some(client.clone()),
                Arc::clone(&outbound_network_policy),
            );
            ctrl.read_welcome(request_timeout).await?;
            return Ok(ctrl);
        }

        let mut ctrl = Self::from_stream(
            FtpControlStream::Plain(stream),
            host,
            connection,
            None,
            outbound_network_policy,
        );
        ctrl.read_welcome(request_timeout).await?;
        info!(
            "Connected to FTP server {}:{} through HTTP proxy {}:{}",
            host, port, proxy.proxy_host, proxy.proxy_port
        );
        Ok(ctrl)
    }

    /// Connect to an explicit FTPS endpoint and perform RFC 4217 setup.
    pub(super) async fn connect_ftps_explicit_at(
        host: &str,
        port: u16,
        socket_addr: std::net::SocketAddr,
        client: &FtpsClient,
        outbound_network_policy: Arc<OutboundNetworkPolicy>,
        request_timeout: Option<Duration>,
    ) -> Result<Self> {
        let (stream, connection) = Self::connect_tcp_at(
            host,
            port,
            socket_addr,
            Arc::clone(&outbound_network_policy),
        )
        .await?;
        let mut plain = Self::from_stream(
            FtpControlStream::Plain(stream),
            host,
            connection,
            None,
            Arc::clone(&outbound_network_policy),
        );
        plain.read_welcome(request_timeout).await?;

        let Self {
            reader,
            host,
            connection,
            ..
        } = plain;
        let stream = match reader.into_inner() {
            FtpControlStream::Plain(stream) => stream,
            FtpControlStream::Tls(_) => unreachable!("fresh FTPS control stream is plain"),
        };
        let tls_stream = client
            .upgrade_control_stream(stream, &host)
            .await
            .map_err(|error| {
                Aria2Error::Network(format!("FTPS control upgrade failed: {}", error))
            })?;

        info!("FTPS control connection established with {}:{}", host, port);
        Ok(Self::from_stream(
            FtpControlStream::Tls(Box::new(tls_stream)),
            &host,
            connection,
            Some(client.clone()),
            outbound_network_policy,
        ))
    }

    /// Connect to an implicit FTPS endpoint where TLS starts immediately.
    pub(super) async fn connect_ftps_implicit_at(
        host: &str,
        port: u16,
        socket_addr: std::net::SocketAddr,
        client: &FtpsClient,
        outbound_network_policy: Arc<OutboundNetworkPolicy>,
        request_timeout: Option<Duration>,
    ) -> Result<Self> {
        let (stream, connection) = Self::connect_tcp_at(
            host,
            port,
            socket_addr,
            Arc::clone(&outbound_network_policy),
        )
        .await?;
        let tls_stream = client
            .perform_tls_handshake(stream, host)
            .await
            .map_err(|error| {
                Aria2Error::Network(format!("FTPS TLS handshake failed: {}", error))
            })?;
        let mut ctrl = Self::from_stream(
            FtpControlStream::Tls(Box::new(tls_stream)),
            host,
            connection,
            Some(client.clone()),
            outbound_network_policy,
        );
        ctrl.read_welcome(request_timeout).await?;

        tls::negotiate_protected_data_channel(ctrl.reader.reader_mut())
            .await
            .map_err(|error| {
                Aria2Error::Network(format!("FTPS data protection failed: {}", error))
            })?;

        info!(
            "Implicit FTPS control connection established with {}:{}",
            host, port
        );
        Ok(ctrl)
    }
}

pub(super) fn map_session_error(error: FtpControlSessionError) -> Aria2Error {
    use aria2_protocol::ftp::connection::control_io::FtpControlReadError;

    match error {
        FtpControlSessionError::ReadTimeout(timeout) => {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!("FTP response timeout after {timeout:?}"),
            })
        }
        FtpControlSessionError::Read(FtpControlReadError::Timeout) => {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: "FTP response timeout".into(),
            })
        }
        FtpControlSessionError::Read(FtpControlReadError::Io(error)) => {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!("FTP read response error: {error}"),
            })
        }
        FtpControlSessionError::Write(error) => {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!("FTP write command failed: {error}"),
            })
        }
        FtpControlSessionError::InvalidResponse(line) => {
            Aria2Error::Recoverable(RecoverableError::FtpProtocolError {
                message: format!("Invalid FTP response line: {line:?}"),
            })
        }
        FtpControlSessionError::InvalidValue(message) => {
            Aria2Error::Recoverable(RecoverableError::FtpProtocolError { message })
        }
        FtpControlSessionError::Rejected { command, response } => {
            if response.code == 550 && matches!(command, "CWD" | "SIZE" | "RETR") {
                Aria2Error::Recoverable(RecoverableError::ResourceNotFound)
            } else {
                let message = match command {
                    "USER" => format!(
                        "Unexpected USER response: {} {}",
                        response.code, response.message
                    ),
                    "PASS" => format!("Login failed: {} {}", response.code, response.message),
                    "TYPE A" => format!(
                        "TYPE A (ASCII) failed: {} {}",
                        response.code, response.message
                    ),
                    "TYPE I" => format!(
                        "TYPE I (binary) failed: {} {}",
                        response.code, response.message
                    ),
                    "PWD" | "CWD" | "PASV" | "PORT" => {
                        format!("{command} failed: {} {}", response.code, response.message)
                    }
                    "EPRT" => format!(
                        "EPRT failed for IPv6: {} {}",
                        response.code, response.message
                    ),
                    "RETR" => format!(
                        "RETR unexpected response: {} {}",
                        response.code, response.message
                    ),
                    _ => format!("{command} failed: {} {}", response.code, response.message),
                };
                Aria2Error::Recoverable(RecoverableError::FtpProtocolError { message })
            }
        }
        FtpControlSessionError::IncompleteResponse => {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: "FTP response ended before CRLF-terminated response was complete".into(),
            })
        }
        FtpControlSessionError::ResponseTooLarge(bytes) => {
            Aria2Error::Recoverable(RecoverableError::TemporaryNetworkFailure {
                message: format!("Max FTP recv buffer reached. length={bytes}"),
            })
        }
    }
}

#[cfg(test)]
mod tests;