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