#![allow(missing_docs)]
mod stream;
mod tunnel;
use http::header::{HeaderMap, HeaderName, HeaderValue};
use hyper::{service::Service, Uri};
use futures::future::TryFutureExt;
use std::{fmt, io, sync::Arc};
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
pub use stream::ProxyStream;
use tokio::io::{AsyncRead, AsyncWrite};
#[cfg(feature = "tls")]
use native_tls::TlsConnector as NativeTlsConnector;
#[cfg(feature = "tls")]
use tokio_native_tls::TlsConnector;
#[cfg(feature = "rustls-base")]
use tokio_rustls::TlsConnector;
use headers::{authorization::Credentials, Authorization, HeaderMapExt, ProxyAuthorization};
#[cfg(feature = "openssl-tls")]
use openssl::ssl::{SslConnector as OpenSslConnector, SslMethod};
#[cfg(feature = "openssl-tls")]
use tokio_openssl::SslStream;
#[cfg(feature = "rustls-base")]
use webpki::DNSNameRef;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug, Clone)]
pub enum Intercept {
All,
Http,
Https,
None,
Custom(Custom),
}
pub trait Dst {
fn scheme(&self) -> Option<&str>;
fn host(&self) -> Option<&str>;
fn port(&self) -> Option<u16>;
}
impl Dst for Uri {
fn scheme(&self) -> Option<&str> {
self.scheme_str()
}
fn host(&self) -> Option<&str> {
self.host()
}
fn port(&self) -> Option<u16> {
self.port_u16()
}
}
#[inline]
pub(crate) fn io_err<E: Into<Box<dyn std::error::Error + Send + Sync>>>(e: E) -> io::Error {
io::Error::new(io::ErrorKind::Other, e)
}
#[derive(Clone)]
pub struct Custom(Arc<dyn Fn(Option<&str>, Option<&str>, Option<u16>) -> bool + Send + Sync>);
impl fmt::Debug for Custom {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "_")
}
}
impl<F: Fn(Option<&str>, Option<&str>, Option<u16>) -> bool + Send + Sync + 'static> From<F>
for Custom
{
fn from(f: F) -> Custom {
Custom(Arc::new(f))
}
}
impl Intercept {
pub fn matches<D: Dst>(&self, uri: &D) -> bool {
match (self, uri.scheme()) {
(&Intercept::All, _)
| (&Intercept::Http, Some("http"))
| (&Intercept::Https, Some("https")) => true,
(&Intercept::Custom(Custom(ref f)), _) => f(uri.scheme(), uri.host(), uri.port()),
_ => false,
}
}
}
impl<F: Fn(Option<&str>, Option<&str>, Option<u16>) -> bool + Send + Sync + 'static> From<F>
for Intercept
{
fn from(f: F) -> Intercept {
Intercept::Custom(f.into())
}
}
#[derive(Clone, Debug)]
pub struct Proxy {
intercept: Intercept,
force_connect: bool,
headers: HeaderMap,
uri: Uri,
}
impl Proxy {
pub fn new<I: Into<Intercept>>(intercept: I, uri: Uri) -> Proxy {
Proxy {
intercept: intercept.into(),
uri: uri,
headers: HeaderMap::new(),
force_connect: false,
}
}
pub fn set_authorization<C: Credentials + Clone>(&mut self, credentials: Authorization<C>) {
match self.intercept {
Intercept::Http => {
self.headers.typed_insert(Authorization(credentials.0));
}
Intercept::Https => {
self.headers.typed_insert(ProxyAuthorization(credentials.0));
}
_ => {
self.headers
.typed_insert(Authorization(credentials.0.clone()));
self.headers.typed_insert(ProxyAuthorization(credentials.0));
}
}
}
pub fn force_connect(&mut self) {
self.force_connect = true;
}
pub fn set_header(&mut self, name: HeaderName, value: HeaderValue) {
self.headers.insert(name, value);
}
pub fn intercept(&self) -> &Intercept {
&self.intercept
}
pub fn headers(&self) -> &HeaderMap {
&self.headers
}
pub fn uri(&self) -> &Uri {
&self.uri
}
}
#[derive(Clone)]
pub struct ProxyConnector<C> {
proxies: Vec<Proxy>,
connector: C,
#[cfg(feature = "tls")]
tls: Option<NativeTlsConnector>,
#[cfg(feature = "rustls-base")]
tls: Option<TlsConnector>,
#[cfg(feature = "openssl-tls")]
tls: Option<OpenSslConnector>,
#[cfg(not(any(feature = "tls", feature = "rustls-base", feature = "openssl-tls")))]
tls: Option<()>,
}
impl<C: fmt::Debug> fmt::Debug for ProxyConnector<C> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(
f,
"ProxyConnector {}{{ proxies: {:?}, connector: {:?} }}",
if self.tls.is_some() {
""
} else {
"(unsecured)"
},
self.proxies,
self.connector
)
}
}
impl<C> ProxyConnector<C> {
#[cfg(feature = "tls")]
pub fn new(connector: C) -> Result<Self, io::Error> {
let tls = NativeTlsConnector::builder()
.build()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(ProxyConnector {
proxies: Vec::new(),
connector: connector,
tls: Some(tls),
})
}
#[cfg(feature = "rustls-base")]
pub fn new(connector: C) -> Result<Self, io::Error> {
let mut config = tokio_rustls::rustls::ClientConfig::new();
#[cfg(feature = "rustls")]
{
config.root_store =
rustls_native_certs::load_native_certs().map_err(|(_store, io)| io)?;
}
#[cfg(feature = "rustls-webpki")]
{
config
.root_store
.add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);
}
let cfg = Arc::new(config);
let tls = TlsConnector::from(cfg);
Ok(ProxyConnector {
proxies: Vec::new(),
connector: connector,
tls: Some(tls),
})
}
#[allow(missing_docs)]
#[cfg(feature = "openssl-tls")]
pub fn new(connector: C) -> Result<Self, io::Error> {
let builder = OpenSslConnector::builder(SslMethod::tls())
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
let tls = builder.build();
Ok(ProxyConnector {
proxies: Vec::new(),
connector: connector,
tls: Some(tls),
})
}
pub fn unsecured(connector: C) -> Self {
ProxyConnector {
proxies: Vec::new(),
connector: connector,
tls: None,
}
}
#[cfg(any(feature = "tls", feature = "rustls-base", feature = "openssl-tls"))]
pub fn from_proxy(connector: C, proxy: Proxy) -> Result<Self, io::Error> {
let mut c = ProxyConnector::new(connector)?;
c.proxies.push(proxy);
Ok(c)
}
pub fn from_proxy_unsecured(connector: C, proxy: Proxy) -> Self {
let mut c = ProxyConnector::unsecured(connector);
c.proxies.push(proxy);
c
}
pub fn with_connector<CC>(self, connector: CC) -> ProxyConnector<CC> {
ProxyConnector {
connector: connector,
proxies: self.proxies,
tls: self.tls,
}
}
#[cfg(any(feature = "tls"))]
pub fn set_tls(&mut self, tls: Option<NativeTlsConnector>) {
self.tls = tls;
}
#[cfg(any(feature = "rustls-base"))]
pub fn set_tls(&mut self, tls: Option<TlsConnector>) {
self.tls = tls;
}
#[cfg(any(feature = "openssl-tls"))]
pub fn set_tls(&mut self, tls: Option<OpenSslConnector>) {
self.tls = tls;
}
pub fn proxies(&self) -> &[Proxy] {
&self.proxies
}
pub fn add_proxy(&mut self, proxy: Proxy) {
self.proxies.push(proxy);
}
pub fn extend_proxies<I: IntoIterator<Item = Proxy>>(&mut self, proxies: I) {
self.proxies.extend(proxies)
}
pub fn http_headers(&self, uri: &Uri) -> Option<&HeaderMap> {
if uri.scheme_str().map_or(true, |s| s != "http") {
return None;
}
self.match_proxy(uri).map(|p| &p.headers)
}
fn match_proxy<D: Dst>(&self, uri: &D) -> Option<&Proxy> {
self.proxies.iter().find(|p| p.intercept.matches(uri))
}
}
macro_rules! mtry {
($e:expr) => {
match $e {
Ok(v) => v,
Err(e) => break Err(e.into()),
}
};
}
impl<C> Service<Uri> for ProxyConnector<C>
where
C: Service<Uri>,
C::Response: AsyncRead + AsyncWrite + Send + Unpin + 'static,
C::Future: Send + 'static,
C::Error: Into<BoxError>,
{
type Response = ProxyStream<C::Response>;
type Error = io::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
match self.connector.poll_ready(cx) {
Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
Poll::Ready(Err(e)) => Poll::Ready(Err(io_err(e.into()))),
Poll::Pending => Poll::Pending,
}
}
fn call(&mut self, uri: Uri) -> Self::Future {
if let (Some(p), Some(host)) = (self.match_proxy(&uri), uri.host()) {
if uri.scheme() == Some(&http::uri::Scheme::HTTPS) || p.force_connect {
let host = host.to_owned();
let port = uri.port_u16().unwrap_or(443);
let tunnel = tunnel::new(&host, port, &p.headers);
let connection =
proxy_dst(&uri, &p.uri).map(|proxy_url| self.connector.call(proxy_url));
let tls = if uri.scheme() == Some(&http::uri::Scheme::HTTPS) {
self.tls.clone()
} else {
None
};
Box::pin(async move {
loop {
let proxy_stream = mtry!(mtry!(connection).await.map_err(io_err));
let tunnel_stream = mtry!(tunnel.with_stream(proxy_stream).await);
break match tls {
#[cfg(feature = "tls")]
Some(tls) => {
let tls = TlsConnector::from(tls);
let secure_stream =
mtry!(tls.connect(&host, tunnel_stream).await.map_err(io_err));
Ok(ProxyStream::Secured(secure_stream))
}
#[cfg(feature = "rustls-base")]
Some(tls) => {
let dnsref =
mtry!(DNSNameRef::try_from_ascii_str(&host).map_err(io_err));
let tls = TlsConnector::from(tls);
let secure_stream =
mtry!(tls.connect(dnsref, tunnel_stream).await.map_err(io_err));
Ok(ProxyStream::Secured(secure_stream))
}
#[cfg(feature = "openssl-tls")]
Some(tls) => {
let config = tls.configure().map_err(io_err)?;
let ssl = config.into_ssl(&host).map_err(io_err)?;
let mut stream = mtry!(SslStream::new(ssl, tunnel_stream));
mtry!(Pin::new(&mut stream).connect().await.map_err(io_err));
Ok(ProxyStream::Secured(stream))
}
#[cfg(not(any(
feature = "tls",
feature = "rustls-base",
feature = "openssl-tls"
)))]
Some(_) => panic!("hyper-proxy was not built with TLS support"),
None => Ok(ProxyStream::Regular(tunnel_stream)),
};
}
})
} else {
match proxy_dst(&uri, &p.uri) {
Ok(proxy_uri) => Box::pin(
self.connector
.call(proxy_uri)
.map_ok(ProxyStream::Regular)
.map_err(|err| io_err(err.into())),
),
Err(err) => Box::pin(futures::future::err(io_err(err))),
}
}
} else {
Box::pin(
self.connector
.call(uri)
.map_ok(ProxyStream::NoProxy)
.map_err(|err| io_err(err.into())),
)
}
}
}
fn proxy_dst(dst: &Uri, proxy: &Uri) -> io::Result<Uri> {
Uri::builder()
.scheme(
proxy
.scheme_str()
.ok_or_else(|| io_err(format!("proxy uri missing scheme: {}", proxy)))?,
)
.authority(
proxy
.authority()
.ok_or_else(|| io_err(format!("proxy uri missing host: {}", proxy)))?
.clone(),
)
.path_and_query(dst.path_and_query().unwrap().clone())
.build()
.map_err(|err| io_err(format!("other error: {}", err)))
}