use tokio::io::BufReader;
use tokio::net::{TcpListener, TcpStream};
use tokio::time::Duration;
#[derive(Debug, Clone)]
pub struct FtpOptions {
pub connect_timeout: Duration,
pub read_timeout: Duration,
pub passive_mode: bool,
pub username: String,
pub password: String,
pub keepalive_interval: Option<Duration>,
pub max_retries: u32,
}
impl Default for FtpOptions {
fn default() -> Self {
Self {
connect_timeout: Duration::from_secs(30),
read_timeout: Duration::from_secs(30),
passive_mode: true,
username: "anonymous".to_string(),
password: "aria2@".to_string(),
keepalive_interval: Some(Duration::from_secs(60)),
max_retries: 3,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FtpResponseClass {
PositivePreliminary,
PositiveCompletion,
PositiveIntermediate,
TransientNegative,
PermanentNegative,
Unknown,
}
impl FtpResponseClass {
pub fn from_code(code: u16) -> Self {
match code {
100..=199 => Self::PositivePreliminary,
200..=299 => Self::PositiveCompletion,
300..=399 => Self::PositiveIntermediate,
400..=499 => Self::TransientNegative,
500..=599 => Self::PermanentNegative,
_ => Self::Unknown,
}
}
pub fn is_success(&self) -> bool {
matches!(
self,
Self::PositivePreliminary | Self::PositiveCompletion | Self::PositiveIntermediate
)
}
pub fn is_transient(&self) -> bool {
*self == Self::TransientNegative
}
pub fn is_permanent(&self) -> bool {
*self == Self::PermanentNegative
}
}
#[derive(Debug, Clone)]
pub struct FtpResponse {
pub code: u16,
pub message: String,
}
impl FtpResponse {
pub fn is_success(&self) -> bool {
(100..400).contains(&self.code)
}
pub fn is_intermediate(&self) -> bool {
(100..200).contains(&self.code)
}
pub fn is_positive_completion(&self) -> bool {
(200..300).contains(&self.code)
}
pub fn is_positive_preliminary(&self) -> bool {
(100..200).contains(&self.code)
}
pub fn class(&self) -> FtpResponseClass {
FtpResponseClass::from_code(self.code)
}
pub fn is_transient_error(&self) -> bool {
self.class().is_transient()
}
pub fn is_permanent_error(&self) -> bool {
self.class().is_permanent()
}
}
pub struct FtpConnection {
pub stream: BufReader<TcpStream>,
pub options: FtpOptions,
#[allow(dead_code)]
pub host: String,
#[allow(dead_code)]
pub port: u16,
}
pub struct FtpActiveDataListener {
listener: TcpListener,
local_addr: std::net::SocketAddr,
}
impl FtpActiveDataListener {
pub fn new(listener: TcpListener, local_addr: std::net::SocketAddr) -> Self {
Self {
listener,
local_addr,
}
}
pub fn local_addr(&self) -> std::net::SocketAddr {
self.local_addr
}
pub fn port(&self) -> u16 {
self.local_addr.port()
}
pub async fn accept(self) -> Result<TcpStream, String> {
self.accept_with_peer()
.await
.map(|(stream, _)| stream)
.map_err(|e| format!("Failed to accept FTP active data connection: {}", e))
}
pub async fn accept_with_peer(self) -> std::io::Result<(TcpStream, std::net::SocketAddr)> {
self.listener.accept().await
}
}