use crate::error::ProxyError;
use crate::negotiator::{negotiate, tunnel_proto, Stream, Target};
use crate::proxy::Proxy;
use crate::resolver::Resolver;
use crate::server::{ClientKey, Pool};
use crate::types::{Proto, Scheme};
use hyper::Uri;
use hyper_util::client::legacy::connect::{Connected, Connection};
use hyper_util::rt::TokioIo;
use std::future::Future;
use std::io;
use std::net::{IpAddr, Ipv4Addr};
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::net::TcpStream;
#[derive(Debug, Clone)]
pub struct RotateConfig {
pub max_tries: usize,
pub timeout: Duration,
}
impl Default for RotateConfig {
fn default() -> Self {
RotateConfig {
max_tries: 3,
timeout: Duration::from_secs(8),
}
}
}
#[derive(Clone)]
pub struct RotatingProxyConnector {
pool: Arc<Pool>,
resolver: Arc<Resolver>,
cfg: RotateConfig,
}
impl RotatingProxyConnector {
pub fn from_pool(pool: Arc<Pool>, resolver: Arc<Resolver>, cfg: RotateConfig) -> Self {
RotatingProxyConnector {
pool,
resolver,
cfg,
}
}
}
pub struct ProxyConn(TokioIo<Stream>);
impl hyper::rt::Read for ProxyConn {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: hyper::rt::ReadBufCursor<'_>,
) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_read(cx, buf)
}
}
impl hyper::rt::Write for ProxyConn {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut self.0).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.0).poll_shutdown(cx)
}
}
impl Connection for ProxyConn {
fn connected(&self) -> Connected {
Connected::new()
}
}
impl tower_service::Service<Uri> for RotatingProxyConnector {
type Response = ProxyConn;
type Error = io::Error;
type Future = Pin<Box<dyn Future<Output = io::Result<ProxyConn>> + Send>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Poll::Ready(Ok(())) }
fn call(&mut self, uri: Uri) -> Self::Future {
let pool = self.pool.clone();
let resolver = self.resolver.clone();
let cfg = self.cfg.clone();
Box::pin(async move { connect(&pool, &resolver, &cfg, uri).await })
}
}
fn connect_proto(proxy: &Proxy, scheme: Scheme) -> Option<Proto> {
tunnel_proto(proxy).or_else(|| {
(scheme == Scheme::Http && proxy.types().contains_key(&Proto::Http)).then_some(Proto::Http)
})
}
async fn connect(
pool: &Pool,
resolver: &Resolver,
cfg: &RotateConfig,
uri: Uri,
) -> io::Result<ProxyConn> {
let scheme = match uri.scheme_str() {
Some("https") => Scheme::Https,
_ => Scheme::Http,
};
let raw_host = uri
.host()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "uri has no host"))?;
let host = raw_host
.strip_prefix('[')
.and_then(|h| h.strip_suffix(']'))
.unwrap_or(raw_host)
.to_string();
let port = uri
.port_u16()
.unwrap_or(if scheme == Scheme::Https { 443 } else { 80 });
let ip = resolver.resolve(&host).await.ok();
let target = Target { host, ip, port };
let key = ClientKey::Ip(IpAddr::V4(Ipv4Addr::UNSPECIFIED));
let mut last: Option<ProxyError> = None;
for _ in 0..cfg.max_tries {
let Some(mut proxy) = pool.get(scheme, &key).await else {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"no proxy available in the pool",
));
};
let Some(proto) = connect_proto(&proxy, scheme) else {
pool.put_ok(proxy);
continue;
};
match dial(&proxy, proto, &target, cfg.timeout).await {
Ok(stream) => {
proxy.record_attempt(Some(0.0), None);
pool.put_ok(proxy);
return Ok(ProxyConn(TokioIo::new(stream)));
}
Err(e) => {
proxy.record_attempt(None, Some(e));
pool.put_failed(proxy); last = Some(e);
}
}
}
Err(io::Error::other(
last.map(|e| e.as_str()).unwrap_or("all proxies failed"),
))
}
async fn dial(
proxy: &Proxy,
proto: crate::types::Proto,
target: &Target,
timeout: Duration,
) -> Result<Stream, ProxyError> {
let tcp =
match tokio::time::timeout(timeout, TcpStream::connect((proxy.host, proxy.port))).await {
Err(_) => return Err(ProxyError::Timeout),
Ok(Err(_)) => return Err(ProxyError::ConnFailed),
Ok(Ok(t)) => t,
};
negotiate(proto, tcp, target, timeout, proxy.auth()).await
}