use tokio::net::TcpStream;
use tracing::{debug, info, warn};
use crate::error::{Aria2Error, Result};
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 HttpProxyTunnel {
config: HttpProxyConfig,
}
impl HttpProxyTunnel {
pub fn new(config: HttpProxyConfig) -> Self {
Self { config }
}
pub async fn connect(&self) -> Result<TcpStream> {
let mut stream = connect_to_proxy(&self.config).await?;
let target = self.config.target_host_port();
let mut auth_nc = 1u32;
let request = self.build_connect_request(None);
debug!("Sending CONNECT request to proxy for {}", target);
write_all_timeout(&mut stream, request.as_bytes(), self.config.write_timeout).await?;
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(head) => {
info!("CONNECT tunnel established to {} via proxy", target);
debug!("Proxy response: {:?}", head);
return Ok(stream);
}
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, "CONNECT", &target, 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 CONNECT with authentication (attempt {})",
auth_nc
);
let request = self.build_connect_request(Some(&auth_value));
write_all_timeout(&mut stream, request.as_bytes(), self.config.write_timeout)
.await?;
}
ProxyResponse::Error {
status_code,
reason,
} => {
return Err(Aria2Error::Network(format!(
"Proxy returned error {} {} for CONNECT to {}",
status_code, reason, target
)));
}
}
}
}
pub(crate) fn build_connect_request(&self, proxy_auth: Option<&str>) -> String {
let target = self.config.target_host_port();
let mut req = format!("CONNECT {} HTTP/1.1\r\nHost: {}\r\n", target, target);
if let Some(auth) = proxy_auth {
req.push_str(&format!("Proxy-Authorization: {}\r\n", auth));
}
req.push_str("Proxy-Connection: keep-alive\r\n");
req.push_str("\r\n");
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(),
)),
}
}
}