Skip to main content

aria2_protocol/ftp/connection/
types.rs

1use tokio::io::BufReader;
2use tokio::net::{TcpListener, TcpStream};
3use tokio::time::Duration;
4
5/// FTP connection configuration options.
6#[derive(Debug, Clone)]
7pub struct FtpOptions {
8    pub connect_timeout: Duration,
9    pub read_timeout: Duration,
10    pub passive_mode: bool,
11    pub username: String,
12    pub password: String,
13    /// Keep-alive interval for control channel (None to disable).
14    pub keepalive_interval: Option<Duration>,
15    /// Maximum number of retry attempts for transient errors.
16    pub max_retries: u32,
17}
18
19impl Default for FtpOptions {
20    fn default() -> Self {
21        Self {
22            connect_timeout: Duration::from_secs(30),
23            read_timeout: Duration::from_secs(30),
24            passive_mode: true,
25            username: "anonymous".to_string(),
26            password: "aria2@".to_string(),
27            keepalive_interval: Some(Duration::from_secs(60)),
28            max_retries: 3,
29        }
30    }
31}
32
33/// FTP response code classification.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum FtpResponseClass {
36    /// Positive Preliminary (1xx): Command accepted, waiting for confirmation.
37    PositivePreliminary,
38    /// Positive Completion (2xx): Command completed successfully.
39    PositiveCompletion,
40    /// Positive Intermediate (3xx): Command accepted, additional info needed.
41    PositiveIntermediate,
42    /// Transient Negative (4xx): Temporary failure, retry may succeed.
43    TransientNegative,
44    /// Permanent Negative (5xx): Permanent failure, do not retry.
45    PermanentNegative,
46    /// Unknown/Invalid response code.
47    Unknown,
48}
49
50impl FtpResponseClass {
51    /// Classify an FTP response code into its category.
52    pub fn from_code(code: u16) -> Self {
53        match code {
54            100..=199 => Self::PositivePreliminary,
55            200..=299 => Self::PositiveCompletion,
56            300..=399 => Self::PositiveIntermediate,
57            400..=499 => Self::TransientNegative,
58            500..=599 => Self::PermanentNegative,
59            _ => Self::Unknown,
60        }
61    }
62
63    /// Check if this response class indicates success (1xx-3xx).
64    pub fn is_success(&self) -> bool {
65        matches!(
66            self,
67            Self::PositivePreliminary | Self::PositiveCompletion | Self::PositiveIntermediate
68        )
69    }
70
71    /// Check if this is a retry-worthy transient error (4xx).
72    pub fn is_transient(&self) -> bool {
73        *self == Self::TransientNegative
74    }
75
76    /// Check if this is a permanent failure (5xx).
77    pub fn is_permanent(&self) -> bool {
78        *self == Self::PermanentNegative
79    }
80}
81
82/// FTP server response with code and message.
83#[derive(Debug, Clone)]
84pub struct FtpResponse {
85    pub code: u16,
86    pub message: String,
87}
88
89impl FtpResponse {
90    pub fn is_success(&self) -> bool {
91        (100..400).contains(&self.code)
92    }
93
94    pub fn is_intermediate(&self) -> bool {
95        (100..200).contains(&self.code)
96    }
97
98    pub fn is_positive_completion(&self) -> bool {
99        (200..300).contains(&self.code)
100    }
101
102    pub fn is_positive_preliminary(&self) -> bool {
103        (100..200).contains(&self.code)
104    }
105
106    /// Get the response class for this response.
107    pub fn class(&self) -> FtpResponseClass {
108        FtpResponseClass::from_code(self.code)
109    }
110
111    /// Check if this response indicates a transient error (retry-worthy).
112    pub fn is_transient_error(&self) -> bool {
113        self.class().is_transient()
114    }
115
116    /// Check if this response indicates a permanent error (do not retry).
117    pub fn is_permanent_error(&self) -> bool {
118        self.class().is_permanent()
119    }
120}
121
122/// FTP control connection state.
123pub struct FtpConnection {
124    pub stream: BufReader<TcpStream>,
125    pub options: FtpOptions,
126    #[allow(dead_code)]
127    pub host: String,
128    #[allow(dead_code)]
129    pub port: u16,
130}
131
132/// A listener retained for one FTP active-mode data transfer.
133///
134/// Active mode is a two-step operation: the client advertises a local
135/// listener with `PORT`/`EPRT`, then accepts the server connection after the
136/// transfer command is sent. Keeping the listener in this value prevents the
137/// socket from being dropped between those steps.
138pub struct FtpActiveDataListener {
139    listener: TcpListener,
140    local_addr: std::net::SocketAddr,
141}
142
143impl FtpActiveDataListener {
144    pub fn new(listener: TcpListener, local_addr: std::net::SocketAddr) -> Self {
145        Self {
146            listener,
147            local_addr,
148        }
149    }
150
151    /// Local address advertised to the FTP server.
152    pub fn local_addr(&self) -> std::net::SocketAddr {
153        self.local_addr
154    }
155
156    /// Local port advertised to the FTP server.
157    pub fn port(&self) -> u16 {
158        self.local_addr.port()
159    }
160
161    /// Accept the server's active-mode data connection.
162    pub async fn accept(self) -> Result<TcpStream, String> {
163        self.accept_with_peer()
164            .await
165            .map(|(stream, _)| stream)
166            .map_err(|e| format!("Failed to accept FTP active data connection: {}", e))
167    }
168
169    /// Accept the connection while retaining the peer address for callers
170    /// that apply their own network policy or diagnostics.
171    pub async fn accept_with_peer(self) -> std::io::Result<(TcpStream, std::net::SocketAddr)> {
172        self.listener.accept().await
173    }
174}