use crate::InvocationError;
use tokio::net::TcpStream;
use tokio_socks::tcp::Socks5Stream;
#[derive(Clone, Debug)]
pub struct Socks5Config {
pub proxy_addr: String,
pub auth: Option<(String, String)>,
}
impl Socks5Config {
pub fn new(proxy_addr: impl Into<String>) -> Self {
Self {
proxy_addr: proxy_addr.into(),
auth: None,
}
}
pub fn with_auth(
proxy_addr: impl Into<String>,
username: impl Into<String>,
password: impl Into<String>,
) -> Self {
Self {
proxy_addr: proxy_addr.into(),
auth: Some((username.into(), password.into())),
}
}
pub async fn connect(&self, target: &str) -> Result<TcpStream, InvocationError> {
tracing::info!("[socks5] Connecting via {} → {target}", self.proxy_addr);
let stream = match &self.auth {
None => Socks5Stream::connect(self.proxy_addr.as_str(), target)
.await
.map_err(|e| InvocationError::Io(std::io::Error::other(e)))?,
Some((user, pass)) => Socks5Stream::connect_with_password(
self.proxy_addr.as_str(),
target,
user.as_str(),
pass.as_str(),
)
.await
.map_err(|e| InvocationError::Io(std::io::Error::other(e)))?,
};
tracing::info!("[socks5] Connected ✓");
Ok(stream.into_inner())
}
}