Skip to main content

aria2_protocol/ftp/connection/
control_io.rs

1//! Transport-independent FTP control-channel I/O primitives.
2//!
3//! Callers establish and configure the stream, then pass its reader or writer
4//! here. This lets the standalone client use a direct TCP stream while the
5//! engine injects address-bound, proxied, or TLS-protected streams.
6
7use std::time::Duration;
8use std::{fmt, io};
9
10use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncWrite, AsyncWriteExt};
11use tokio::time::timeout;
12
13#[derive(Debug)]
14pub enum FtpControlReadError {
15    Timeout,
16    Io(io::Error),
17}
18
19impl fmt::Display for FtpControlReadError {
20    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
21        match self {
22            Self::Timeout => formatter.write_str("FTP control response timed out"),
23            Self::Io(error) => error.fmt(formatter),
24        }
25    }
26}
27
28impl std::error::Error for FtpControlReadError {
29    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
30        match self {
31            Self::Timeout => None,
32            Self::Io(error) => Some(error),
33        }
34    }
35}
36
37#[derive(Debug)]
38pub enum FtpControlWriteError {
39    Command(io::Error),
40    Terminator(io::Error),
41    Flush(io::Error),
42}
43
44impl fmt::Display for FtpControlWriteError {
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Self::Command(error) | Self::Terminator(error) | Self::Flush(error) => {
48                error.fmt(formatter)
49            }
50        }
51    }
52}
53
54impl std::error::Error for FtpControlWriteError {
55    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
56        match self {
57            Self::Command(error) | Self::Terminator(error) | Self::Flush(error) => Some(error),
58        }
59    }
60}
61
62/// Read one FTP control line under the caller's timeout policy.
63pub async fn read_control_line<R>(
64    reader: &mut R,
65    line: &mut String,
66    timeout_duration: Duration,
67) -> Result<usize, FtpControlReadError>
68where
69    R: AsyncBufRead + Unpin,
70{
71    match timeout(timeout_duration, reader.read_line(line)).await {
72        Ok(Ok(bytes_read)) => Ok(bytes_read),
73        Ok(Err(error)) => Err(FtpControlReadError::Io(error)),
74        Err(_) => Err(FtpControlReadError::Timeout),
75    }
76}
77
78/// Write one FTP command and its CRLF terminator to an injected stream.
79pub async fn write_control_command<W>(
80    writer: &mut W,
81    command: &str,
82) -> Result<(), FtpControlWriteError>
83where
84    W: AsyncWrite + Unpin,
85{
86    writer
87        .write_all(command.as_bytes())
88        .await
89        .map_err(FtpControlWriteError::Command)?;
90    writer
91        .write_all(b"\r\n")
92        .await
93        .map_err(FtpControlWriteError::Terminator)?;
94    writer.flush().await.map_err(FtpControlWriteError::Flush)
95}