Skip to main content

aria2_protocol/ftp/
connection.rs

1//! FTP control connection and response handling.
2
3mod commands;
4mod data;
5mod types;
6
7pub use types::{FtpActiveDataListener, FtpConnection, FtpOptions, FtpResponse, FtpResponseClass};
8
9use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
10use tokio::net::TcpStream;
11use tokio::time::timeout;
12use tracing::{debug, info};
13
14impl FtpConnection {
15    /// Establish a control connection and consume the server welcome response.
16    pub async fn connect(
17        host: &str,
18        port: u16,
19        options: Option<FtpOptions>,
20    ) -> Result<Self, String> {
21        let options = options.unwrap_or_default();
22        info!("FTP connecting: {}:{}", host, port);
23
24        let stream = timeout(options.connect_timeout, TcpStream::connect((host, port)))
25            .await
26            .map_err(|_| {
27                format!(
28                    "FTP connection timeout ({}s)",
29                    options.connect_timeout.as_secs()
30                )
31            })?
32            .map_err(|e| format!("FTP connection failed: {}", e))?;
33
34        let mut conn = Self {
35            stream: tokio::io::BufReader::new(stream),
36            options,
37            host: host.to_string(),
38            port,
39        };
40
41        let welcome = conn.read_response().await?;
42        if !welcome.is_positive_completion() && !welcome.is_positive_preliminary() {
43            return Err(format!(
44                "FTP server refused connection: {} {}",
45                welcome.code, welcome.message
46            ));
47        }
48        debug!("FTP connected: {}", welcome.message);
49
50        Ok(conn)
51    }
52
53    async fn send_command(&mut self, command: &str) -> Result<(), String> {
54        debug!("FTP command: {}", command.trim());
55        self.stream
56            .write_all(command.as_bytes())
57            .await
58            .map_err(|e| format!("Failed to send FTP command: {}", e))?;
59        self.stream
60            .write_all(b"\r\n")
61            .await
62            .map_err(|e| format!("Failed to send newline: {}", e))?;
63        self.stream
64            .flush()
65            .await
66            .map_err(|e| format!("Failed to flush buffer: {}", e))?;
67        Ok(())
68    }
69
70    /// Read one FTP response, including multiline responses.
71    pub async fn read_response(&mut self) -> Result<FtpResponse, String> {
72        let mut line = String::new();
73        let mut code: Option<u16> = None;
74        let mut message = String::new();
75        let mut is_multiline = false;
76
77        loop {
78            line.clear();
79            let bytes_read = timeout(self.options.read_timeout, self.stream.read_line(&mut line))
80                .await
81                .map_err(|_| "FTP read timeout".to_string())?
82                .map_err(|e| format!("Failed to read FTP response: {}", e))?;
83
84            if bytes_read == 0 {
85                break;
86            }
87
88            let trimmed = line.trim_end();
89            if trimmed.len() < 4 {
90                continue;
91            }
92
93            let response_code: u16 = trimmed[..3].parse().unwrap_or(0);
94
95            if code.is_none() {
96                code = Some(response_code);
97            }
98
99            let separator = trimmed.as_bytes()[3];
100            if separator == b'-' && !is_multiline {
101                is_multiline = true;
102                message.push_str(&trimmed[4..]);
103                message.push('\n');
104            } else if separator == b' '
105                || (is_multiline && trimmed.starts_with(&format!("{:3} ", code.unwrap_or(0))))
106            {
107                message.push_str(&trimmed[4..]);
108                break;
109            } else if is_multiline {
110                message.push_str(&trimmed[4..]);
111                message.push('\n');
112            }
113        }
114
115        let code_val = code.unwrap_or(0);
116        debug!("FTP response: {} {}", code_val, message.trim());
117        Ok(FtpResponse {
118            code: code_val,
119            message,
120        })
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use tokio::time::Duration;
128
129    #[test]
130    fn test_ftp_response_checks() {
131        let ok = FtpResponse {
132            code: 226,
133            message: "Transfer complete".into(),
134        };
135        assert!(ok.is_success());
136        assert!(ok.is_positive_completion());
137        assert!(!ok.is_permanent_error());
138        assert!(!ok.is_transient_error());
139
140        let intermediate = FtpResponse {
141            code: 150,
142            message: "Opening data channel".into(),
143        };
144        assert!(intermediate.is_success());
145        assert!(intermediate.is_positive_preliminary());
146
147        let error = FtpResponse {
148            code: 550,
149            message: "File not found".into(),
150        };
151        assert!(!error.is_success());
152        assert!(error.is_permanent_error());
153        assert!(!error.is_transient_error());
154
155        let transient = FtpResponse {
156            code: 425,
157            message: "Can't open data connection".into(),
158        };
159        assert!(transient.is_transient_error());
160        assert!(!transient.is_permanent_error());
161    }
162
163    #[test]
164    fn test_response_class_classification() {
165        assert_eq!(
166            FtpResponseClass::from_code(150),
167            FtpResponseClass::PositivePreliminary
168        );
169        assert_eq!(
170            FtpResponseClass::from_code(226),
171            FtpResponseClass::PositiveCompletion
172        );
173        assert_eq!(
174            FtpResponseClass::from_code(331),
175            FtpResponseClass::PositiveIntermediate
176        );
177        assert_eq!(
178            FtpResponseClass::from_code(425),
179            FtpResponseClass::TransientNegative
180        );
181        assert_eq!(
182            FtpResponseClass::from_code(550),
183            FtpResponseClass::PermanentNegative
184        );
185        assert_eq!(FtpResponseClass::from_code(999), FtpResponseClass::Unknown);
186    }
187
188    #[test]
189    fn test_response_class_methods() {
190        let prelim = FtpResponseClass::PositivePreliminary;
191        assert!(prelim.is_success());
192        assert!(!prelim.is_transient());
193        assert!(!prelim.is_permanent());
194
195        let transient = FtpResponseClass::TransientNegative;
196        assert!(!transient.is_success());
197        assert!(transient.is_transient());
198        assert!(!transient.is_permanent());
199
200        let permanent = FtpResponseClass::PermanentNegative;
201        assert!(!permanent.is_success());
202        assert!(!permanent.is_transient());
203        assert!(permanent.is_permanent());
204    }
205
206    #[test]
207    fn test_parse_pasv() {
208        let msg = "Entering Passive Mode (192,168,1,1,195,123)";
209        let result = FtpConnection::parse_pasv_response(msg);
210        assert!(result.is_some());
211        let (host, port) = result.unwrap();
212        assert_eq!(host, "192.168.1.1");
213        assert_eq!(port, 195 * 256 + 123);
214    }
215
216    #[test]
217    fn test_parse_pasv_various_formats() {
218        let msg1 = "227 Entering Passive Mode (192,168,1,100,200,10)";
219        let result1 = FtpConnection::parse_pasv_response(msg1);
220        assert_eq!(result1, Some(("192.168.1.100".to_string(), 200 * 256 + 10)));
221
222        let msg2 = "(10,0,0,1,0,21)";
223        let result2 = FtpConnection::parse_pasv_response(msg2);
224        assert_eq!(result2, Some(("10.0.0.1".to_string(), 21)));
225
226        let msg3 = "192,168,1,1,195,123";
227        let result3 = FtpConnection::parse_pasv_response(msg3);
228        assert!(result3.is_none());
229
230        let msg4 = "(192,168,1,1,195)";
231        let result4 = FtpConnection::parse_pasv_response(msg4);
232        assert!(result4.is_none());
233    }
234
235    #[test]
236    fn test_parse_epsv() {
237        let msg = "Entering Extended Passive Mode (|||50001|)";
238        let result = FtpConnection::parse_epsv_response(msg);
239        assert_eq!(result, Some(50001));
240    }
241
242    #[test]
243    fn test_parse_epsv_various_formats() {
244        let msg1 = "229 |||50001|";
245        let result1 = FtpConnection::parse_epsv_response(msg1);
246        assert_eq!(result1, Some(50001));
247
248        let msg2 = "Entering Extended Passive Mode (|||60000|)";
249        let result2 = FtpConnection::parse_epsv_response(msg2);
250        assert_eq!(result2, Some(60000));
251
252        let msg3 = "50001";
253        let result3 = FtpConnection::parse_epsv_response(msg3);
254        assert!(result3.is_none());
255    }
256
257    #[test]
258    fn test_ftp_options_default() {
259        let opts = FtpOptions::default();
260        assert_eq!(opts.username, "anonymous");
261        assert_eq!(opts.password, "aria2@");
262        assert!(opts.passive_mode);
263        assert_eq!(opts.connect_timeout, Duration::from_secs(30));
264        assert_eq!(opts.read_timeout, Duration::from_secs(30));
265        assert!(opts.keepalive_interval.is_some());
266        assert_eq!(opts.keepalive_interval.unwrap(), Duration::from_secs(60));
267        assert_eq!(opts.max_retries, 3);
268    }
269
270    #[test]
271    fn test_build_port_command_ipv4() {
272        let octets: [u8; 4] = [192, 168, 1, 100];
273        let port: u16 = 50000;
274        let p1 = port / 256;
275        let p2 = port % 256;
276        let port_cmd = format!(
277            "PORT {},{},{},{},{},{}",
278            octets[0], octets[1], octets[2], octets[3], p1, p2
279        );
280        assert_eq!(port_cmd, "PORT 192,168,1,100,195,80");
281    }
282
283    #[test]
284    fn test_build_eprt_command() {
285        let addr = "192.168.1.100";
286        let port: u16 = 50001;
287        let eprt_cmd = format!("EPRT |1|{}|{}", addr, port);
288        assert_eq!(eprt_cmd, "EPRT |1|192.168.1.100|50001");
289
290        let addr_v6 = "::1";
291        let eprt_cmd_v6 = format!("EPRT |2|{}|{}", addr_v6, port);
292        assert_eq!(eprt_cmd_v6, "EPRT |2|::1|50001");
293    }
294}