use tokio::net::TcpStream;
use tracing::{debug, info, warn};
use crate::error::{Aria2Error, Result};
use crate::http::header_processor::HttpResponseHead;
use super::auth::build_proxy_auth_header;
use super::config::HttpProxyConfig;
use super::io::{MAX_AUTH_RETRIES, connect_to_proxy, read_proxy_response, write_all_timeout};
use super::response::ProxyResponse;
pub struct HttpProxyForward {
config: HttpProxyConfig,
}
impl HttpProxyForward {
pub fn new(config: HttpProxyConfig) -> Self {
Self { config }
}
pub async fn connect(&self, skip_handshake: bool) -> Result<TcpStream> {
let mut stream = connect_to_proxy(&self.config).await?;
if skip_handshake {
return Ok(stream);
}
let target_url = format!(
"http://{}:{}",
self.config.target_host, self.config.target_port
);
let probe_request = self.build_forward_request("HEAD", &target_url, "/", None);
debug!("Sending probe HEAD request to proxy for {}", target_url);
write_all_timeout(
&mut stream,
probe_request.as_bytes(),
self.config.write_timeout,
)
.await?;
let mut auth_nc = 1u32;
loop {
let head = read_proxy_response(&mut stream, self.config.read_timeout).await?;
let proxy_resp = ProxyResponse::from_head(head);
match proxy_resp {
ProxyResponse::Connected(_) => {
info!("Forward proxy connection ready for {}", target_url);
drop(stream);
return connect_to_proxy(&self.config).await;
}
ProxyResponse::AuthRequired { response } => {
let (username, password) = self.get_credentials()?;
if auth_nc > MAX_AUTH_RETRIES {
return Err(Aria2Error::Network(
"Proxy authentication failed after max retries".to_string(),
));
}
let auth_value = build_proxy_auth_header(
&response,
&username,
&password,
"HEAD",
&target_url,
auth_nc,
)
.ok_or_else(|| {
Aria2Error::Network(
"Proxy requires auth but no supported scheme found".to_string(),
)
})?;
auth_nc += 1;
warn!(
"Proxy returned 407, retrying with authentication (attempt {})",
auth_nc
);
drop(stream);
stream = connect_to_proxy(&self.config).await?;
let retry_request =
self.build_forward_request("HEAD", &target_url, "/", Some(&auth_value));
write_all_timeout(
&mut stream,
retry_request.as_bytes(),
self.config.write_timeout,
)
.await?;
}
ProxyResponse::Error {
status_code,
reason,
} => {
warn!(
"Proxy returned {} {} on probe, returning stream for caller to retry",
status_code, reason
);
drop(stream);
return connect_to_proxy(&self.config).await;
}
}
}
}
pub fn build_forward_request(
&self,
method: &str,
full_url: &str,
path: &str,
proxy_auth: Option<&str>,
) -> String {
let mut req = format!("{} {} HTTP/1.1\r\n", method, full_url);
req.push_str(&format!("Host: {}\r\n", self.config.target_host_port()));
if self.config.target_port != 80 {
}
if let Some(auth) = proxy_auth {
req.push_str(&format!("Proxy-Authorization: {}\r\n", auth));
}
req.push_str(&format!(
"User-Agent: {}\r\nAccept: */*\r\nConnection: close\r\n\r\n",
crate::constants::USER_AGENT
));
let _ = path; req
}
pub(crate) fn get_credentials(&self) -> Result<(String, String)> {
match (&self.config.proxy_username, &self.config.proxy_password) {
(Some(u), Some(p)) => Ok((u.clone(), p.clone())),
(Some(u), None) => Ok((u.clone(), String::new())),
_ => Err(Aria2Error::Network(
"Proxy requires authentication but no credentials provided".to_string(),
)),
}
}
}
pub async fn forward_get_with_auth(
config: &HttpProxyConfig,
path: &str,
) -> Result<(TcpStream, HttpResponseHead)> {
let full_url = format!(
"http://{}:{}{}",
config.target_host, config.target_port, path
);
let mut stream = connect_to_proxy(config).await?;
let mut auth_nc = 1u32;
let mut current_auth: Option<String> = None;
loop {
let request = if let Some(ref auth) = current_auth {
format!(
"GET {} HTTP/1.1\r\nHost: {}\r\nProxy-Authorization: {}\r\nUser-Agent: {}\r\nAccept: */*\r\nConnection: close\r\n\r\n",
full_url,
config.target_host_port(),
auth,
crate::constants::USER_AGENT
)
} else {
format!(
"GET {} HTTP/1.1\r\nHost: {}\r\nUser-Agent: {}\r\nAccept: */*\r\nConnection: close\r\n\r\n",
full_url,
config.target_host_port(),
crate::constants::USER_AGENT
)
};
write_all_timeout(&mut stream, request.as_bytes(), config.write_timeout).await?;
let head = read_proxy_response(&mut stream, config.read_timeout).await?;
let proxy_resp = ProxyResponse::from_head(head);
match proxy_resp {
ProxyResponse::Connected(head) => {
return Ok((stream, head));
}
ProxyResponse::AuthRequired { response } => {
let username = config.proxy_username.as_deref().unwrap_or("");
let password = config.proxy_password.as_deref().unwrap_or("");
if username.is_empty() && config.proxy_username.is_none() {
return Err(Aria2Error::Network(
"Proxy requires authentication but no credentials provided".to_string(),
));
}
if auth_nc > MAX_AUTH_RETRIES {
return Err(Aria2Error::Network(
"Proxy authentication failed after max retries".to_string(),
));
}
let auth_value = build_proxy_auth_header(
&response, username, password, "GET", &full_url, auth_nc,
)
.ok_or_else(|| {
Aria2Error::Network(
"Proxy requires auth but no supported scheme found".to_string(),
)
})?;
auth_nc += 1;
current_auth = Some(auth_value);
warn!(
"Proxy returned 407, retrying GET with auth (attempt {})",
auth_nc
);
drop(stream);
stream = connect_to_proxy(config).await?;
}
ProxyResponse::Error {
status_code,
reason,
} => {
return Err(Aria2Error::Network(format!(
"Proxy returned error {} {} for GET {}",
status_code, reason, full_url
)));
}
}
}
}