Skip to main content

aria2_protocol/ftp/connection/
commands.rs

1use 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    /// Send ABOR command to abort a transfer in progress.
115    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    /// Send TYPE A command for ASCII mode transfer.
142    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    /// Send NOOP command for keep-alive / connection test.
153    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    /// Run the control-channel keep-alive loop.
166    ///
167    /// The caller must dedicate this mutable connection to the loop while it
168    /// is running. A shared background task cannot safely write `NOOP` through
169    /// the same stream that another operation is using.
170    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
183#[cfg(test)]
184mod tests {
185    use super::*;
186    use crate::ftp::connection::FtpOptions;
187    use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
188    use tokio::net::{TcpListener, TcpStream};
189    use tokio::time::{Duration, timeout};
190
191    #[tokio::test]
192    async fn run_keepalive_sends_noop_on_the_control_stream() {
193        let listener = TcpListener::bind("127.0.0.1:0")
194            .await
195            .expect("bind FTP control listener");
196        let address = listener
197            .local_addr()
198            .expect("read control listener address");
199
200        let server = tokio::spawn(async move {
201            let (stream, _) = listener
202                .accept()
203                .await
204                .expect("accept FTP control connection");
205            let mut reader = BufReader::new(stream);
206            let mut command = String::new();
207            reader
208                .read_line(&mut command)
209                .await
210                .expect("read NOOP command");
211            assert_eq!(command, "NOOP\r\n");
212            reader
213                .get_mut()
214                .write_all(b"200 NOOP ok\r\n")
215                .await
216                .expect("write NOOP response");
217        });
218
219        let stream = TcpStream::connect(address)
220            .await
221            .expect("connect FTP control stream");
222        let options = FtpOptions {
223            keepalive_interval: Some(Duration::from_millis(1)),
224            ..Default::default()
225        };
226        let mut connection = FtpConnection {
227            stream: BufReader::new(stream),
228            options,
229            host: "localhost".to_string(),
230            port: address.port(),
231        };
232
233        let result = timeout(Duration::from_secs(1), connection.run_keepalive())
234            .await
235            .expect("keepalive should observe the closed test server");
236        assert!(result.is_err());
237        server.await.expect("FTP test server should finish");
238    }
239}