aria2_protocol/ftp/connection/
commands.rs1use tokio::io::AsyncWriteExt;
2use tokio::time::{Duration, interval};
3use tracing::{debug, info, warn};
4
5use super::FtpConnection;
6
7impl FtpConnection {
8 pub async fn login(&mut self) -> Result<(), String> {
9 debug!("Sending USER command: {}", self.options.username);
10 self.send_command(&format!("USER {}", self.options.username))
11 .await?;
12 let resp = self.read_response().await?;
13
14 if resp.code == 331 || resp.code == 332 {
15 debug!("Password required, sending PASS command");
16 self.send_command(&format!("PASS {}", self.options.password))
17 .await?;
18 let pass_resp = self.read_response().await?;
19 if !pass_resp.is_positive_completion() {
20 return Err(format!(
21 "FTP login failed: {} {}",
22 pass_resp.code, pass_resp.message
23 ));
24 }
25 info!("FTP login successful");
26 } else if !resp.is_positive_completion() {
27 return Err(format!("FTP login failed: {} {}", resp.code, resp.message));
28 } else {
29 info!("FTP login successful (no password required)");
30 }
31
32 Ok(())
33 }
34
35 pub async fn cwd(&mut self, path: &str) -> Result<(), String> {
36 debug!("Changing directory: {}", path);
37 self.send_command(&format!("CWD {}", path)).await?;
38 let resp = self.read_response().await?;
39 if !resp.is_positive_completion() {
40 return Err(format!("CWD failed: {} {}", resp.code, resp.message));
41 }
42 Ok(())
43 }
44
45 pub async fn size(&mut self, filename: &str) -> Result<u64, String> {
46 debug!("Querying file size: {}", filename);
47 self.send_command(&format!("SIZE {}", filename)).await?;
48 let resp = self.read_response().await?;
49 if resp.code == 213 {
50 let size_str = resp.message.trim();
51 size_str
52 .parse::<u64>()
53 .map_err(|e| format!("Failed to parse file size: {} ({})", e, size_str))
54 } else {
55 Err(format!(
56 "SIZE command failed: {} {}",
57 resp.code, resp.message
58 ))
59 }
60 }
61
62 pub async fn mdtm(&mut self, filename: &str) -> Result<String, String> {
63 debug!("Querying modification time: {}", filename);
64 self.send_command(&format!("MDTM {}", filename)).await?;
65 let resp = self.read_response().await?;
66 if resp.code == 213 {
67 Ok(resp.message.trim().to_string())
68 } else {
69 Err(format!(
70 "MDTM command failed: {} {}",
71 resp.code, resp.message
72 ))
73 }
74 }
75
76 pub async fn rest(&mut self, offset: u64) -> Result<(), String> {
77 debug!("Setting resume offset: {}", offset);
78 self.send_command(&format!("REST {}", offset)).await?;
79 let resp = self.read_response().await?;
80 if resp.code != 350 {
81 return Err(format!("REST failed: {} {}", resp.code, resp.message));
82 }
83 Ok(())
84 }
85
86 pub async fn retr(&mut self, filename: &str) -> Result<(), String> {
87 debug!("Preparing to download file: {}", filename);
88 self.send_command(&format!("RETR {}", filename)).await?;
89 let resp = self.read_response().await?;
90 if !resp.is_positive_preliminary() {
91 return Err(format!("RETR failed: {} {}", resp.code, resp.message));
92 }
93 Ok(())
94 }
95
96 pub async fn type_image(&mut self) -> Result<(), String> {
97 debug!("Setting transfer type to binary (I)");
98 self.send_command("TYPE I").await?;
99 let resp = self.read_response().await?;
100 if !resp.is_positive_completion() {
101 return Err(format!("TYPE I failed: {} {}", resp.code, resp.message));
102 }
103 Ok(())
104 }
105
106 pub async fn quit(mut self) -> Result<(), String> {
107 debug!("Sending QUIT command");
108 self.send_command("QUIT").await?;
109 let resp = self.read_response().await?;
110 info!("FTP disconnected: {}", resp.message);
111 Ok(())
112 }
113
114 pub async fn abor(&mut self) -> Result<(), String> {
116 debug!("Sending ABOR command to abort transfer");
117 self.stream
118 .get_mut()
119 .write_all(b"\xff\xf4")
120 .await
121 .map_err(|e| format!("Failed to send Telnet IP: {}", e))?;
122 self.stream
123 .get_mut()
124 .flush()
125 .await
126 .map_err(|e| format!("Failed to flush buffer: {}", e))?;
127
128 tokio::time::sleep(Duration::from_millis(100)).await;
129
130 self.send_command("ABOR").await?;
131 let resp = self.read_response().await?;
132 if resp.code == 226 || resp.code == 225 {
133 debug!("Transfer successfully aborted: {}", resp.message);
134 Ok(())
135 } else {
136 warn!("ABOR response unusual: {} {}", resp.code, resp.message);
137 Ok(())
138 }
139 }
140
141 pub async fn type_ascii(&mut self) -> Result<(), String> {
143 debug!("Setting transfer type to ASCII (A)");
144 self.send_command("TYPE A").await?;
145 let resp = self.read_response().await?;
146 if !resp.is_positive_completion() {
147 return Err(format!("TYPE A failed: {} {}", resp.code, resp.message));
148 }
149 Ok(())
150 }
151
152 pub async fn noop(&mut self) -> Result<(), String> {
154 debug!("Sending NOOP keep-alive command");
155 self.send_command("NOOP").await?;
156 let resp = self.read_response().await?;
157 if resp.code == 200 {
158 debug!("NOOP keep-alive successful");
159 Ok(())
160 } else {
161 Err(format!("NOOP failed: {} {}", resp.code, resp.message))
162 }
163 }
164
165 pub async fn run_keepalive(&mut self) -> Result<(), String> {
171 let Some(keepalive_duration) = self.options.keepalive_interval else {
172 return Ok(());
173 };
174
175 let mut ticker = interval(keepalive_duration);
176 loop {
177 ticker.tick().await;
178 self.noop().await?;
179 }
180 }
181
182 #[deprecated(note = "use run_keepalive with an exclusively owned connection")]
187 pub fn start_keepalive(&self) -> Option<tokio::task::JoinHandle<()>> {
188 let keepalive_duration = self.options.keepalive_interval?;
189
190 Some(tokio::spawn(async move {
191 let mut ticker = interval(keepalive_duration);
192 loop {
193 ticker.tick().await;
194 debug!("FTP keep-alive tick");
195 }
196 }))
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203 use crate::ftp::connection::FtpOptions;
204 use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
205 use tokio::net::{TcpListener, TcpStream};
206 use tokio::time::{Duration, timeout};
207
208 #[tokio::test]
209 async fn run_keepalive_sends_noop_on_the_control_stream() {
210 let listener = TcpListener::bind("127.0.0.1:0")
211 .await
212 .expect("bind FTP control listener");
213 let address = listener
214 .local_addr()
215 .expect("read control listener address");
216
217 let server = tokio::spawn(async move {
218 let (stream, _) = listener
219 .accept()
220 .await
221 .expect("accept FTP control connection");
222 let mut reader = BufReader::new(stream);
223 let mut command = String::new();
224 reader
225 .read_line(&mut command)
226 .await
227 .expect("read NOOP command");
228 assert_eq!(command, "NOOP\r\n");
229 reader
230 .get_mut()
231 .write_all(b"200 NOOP ok\r\n")
232 .await
233 .expect("write NOOP response");
234 });
235
236 let stream = TcpStream::connect(address)
237 .await
238 .expect("connect FTP control stream");
239 let options = FtpOptions {
240 keepalive_interval: Some(Duration::from_millis(1)),
241 ..Default::default()
242 };
243 let mut connection = FtpConnection {
244 stream: BufReader::new(stream),
245 options,
246 host: "localhost".to_string(),
247 port: address.port(),
248 };
249
250 let result = timeout(Duration::from_secs(1), connection.run_keepalive())
251 .await
252 .expect("keepalive should observe the closed test server");
253 assert!(result.is_err());
254 server.await.expect("FTP test server should finish");
255 }
256}