use std::time::Duration;
use tracing::debug;
use crate::error::{Aria2Error, Result};
use aria2_protocol::proxy::{ProxyProtocol, ProxyUrl};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProxyType {
Http,
Https,
Socks4,
Socks5,
}
impl std::fmt::Display for ProxyType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ProxyType::Http => write!(f, "HTTP"),
ProxyType::Https => write!(f, "HTTPS"),
ProxyType::Socks4 => write!(f, "SOCKS4"),
ProxyType::Socks5 => write!(f, "SOCKS5"),
}
}
}
#[derive(Debug, Clone)]
pub struct HttpProxyConfig {
pub proxy_host: String,
pub proxy_port: u16,
pub proxy_type: ProxyType,
pub proxy_username: Option<String>,
pub proxy_password: Option<String>,
pub target_host: String,
pub target_port: u16,
pub connect_timeout: Duration,
pub read_timeout: Duration,
pub write_timeout: Duration,
}
impl HttpProxyConfig {
pub fn new(proxy_host: String, proxy_port: u16, target_host: String, target_port: u16) -> Self {
Self {
proxy_host,
proxy_port,
proxy_type: ProxyType::Http,
proxy_username: None,
proxy_password: None,
target_host,
target_port,
connect_timeout: Duration::from_secs(30),
read_timeout: Duration::from_secs(60),
write_timeout: Duration::from_secs(60),
}
}
pub fn with_type(
proxy_type: ProxyType,
proxy_host: String,
proxy_port: u16,
target_host: String,
target_port: u16,
) -> Self {
Self {
proxy_host,
proxy_port,
proxy_type,
proxy_username: None,
proxy_password: None,
target_host,
target_port,
connect_timeout: Duration::from_secs(30),
read_timeout: Duration::from_secs(60),
write_timeout: Duration::from_secs(60),
}
}
pub fn with_credentials(mut self, username: String, password: String) -> Self {
self.proxy_username = Some(username);
self.proxy_password = Some(password);
self
}
pub fn from_proxy_url(proxy_url: &str, target_host: String, target_port: u16) -> Result<Self> {
let parsed = ProxyUrl::parse(proxy_url)
.map_err(|e| Aria2Error::Parse(format!("Invalid proxy URL: {e}")))?;
let proxy_type = match parsed.protocol {
ProxyProtocol::Http => ProxyType::Http,
ProxyProtocol::Https => ProxyType::Https,
ProxyProtocol::Socks4 => ProxyType::Socks4,
ProxyProtocol::Socks5 => ProxyType::Socks5,
};
let mut config = Self::with_type(
proxy_type,
parsed.host,
parsed.port,
target_host,
target_port,
);
if let Some(user) = parsed.username {
config.proxy_username = Some(user);
}
if let Some(pass) = parsed.password {
config.proxy_password = Some(pass);
}
debug!(
"Parsed proxy URL: type={}, host={}, port={}, has_auth={}",
config.proxy_type,
config.proxy_host,
config.proxy_port,
config.proxy_username.is_some()
);
Ok(config)
}
pub fn is_socks(&self) -> bool {
matches!(self.proxy_type, ProxyType::Socks4 | ProxyType::Socks5)
}
pub fn is_http_proxy(&self) -> bool {
matches!(self.proxy_type, ProxyType::Http | ProxyType::Https)
}
pub(crate) fn target_host_port(&self) -> String {
format!("{}:{}", self.target_host, self.target_port)
}
}