use super::navigation::{is_link_local_or_metadata, is_localhost};
use crate::tools::web::ssrf;
use hyper_util::client::proxy::matcher::{Intercept, Matcher};
use rho_browser::proxy::upstream::Upstream;
use rho_browser::proxy::{Connect, Destination, Host};
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::Arc;
use tokio::net::TcpStream;
pub(crate) fn connect() -> Result<Connect, String> {
let proxies = Arc::new(user_proxies(Matcher::from_system())?);
Ok(Arc::new(move |destination| {
let proxies = Arc::clone(&proxies);
Box::pin(async move { open(&destination, &proxies).await })
}))
}
fn user_proxies(proxies: Matcher) -> Result<Matcher, String> {
for url in [
"http://example.com/",
"https://example.com/",
"http://rho-proxy-check.invalid/",
"https://rho-proxy-check.invalid/",
] {
if let Some(intercept) = proxies.intercept(&url.parse().expect("a valid URI")) {
UserProxy::of(&intercept)?;
}
}
Ok(proxies)
}
async fn open(destination: &Destination, proxies: &Matcher) -> io::Result<TcpStream> {
match route(destination, proxies).await? {
Route::Direct(addresses) => rho_browser::proxy::connect_first(&addresses).await,
Route::ThroughAt {
upstream,
addresses,
} => {
rho_browser::proxy::race(&addresses, move |address| {
let upstream = upstream.clone();
async move {
let to = Destination {
host: Host::Ip(address.ip()),
port: address.port(),
};
upstream.connect(&to).await
}
})
.await
}
Route::ThroughNamed { upstream, to } => upstream.connect(&to).await,
Route::Refused(reason) => Err(io::Error::new(io::ErrorKind::PermissionDenied, reason)),
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Route {
Direct(Vec<SocketAddr>),
ThroughAt {
upstream: Upstream,
addresses: Vec<SocketAddr>,
},
ThroughNamed { upstream: Upstream, to: Destination },
Refused(String),
}
#[derive(Clone, Copy)]
enum Named<'a> {
Ip(IpAddr),
Name(&'a str),
}
impl std::fmt::Display for Named<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Ip(ip) => write!(f, "{ip}"),
Self::Name(name) => f.write_str(name),
}
}
}
pub(super) async fn route(destination: &Destination, proxies: &Matcher) -> io::Result<Route> {
let port = destination.port;
let named = match &destination.host {
Host::Ip(ip) => Named::Ip(*ip),
Host::Name(name) => match name.trim_matches(['[', ']']).parse::<IpAddr>() {
Ok(ip) => Named::Ip(ip),
Err(_) => Named::Name(name),
},
};
match named {
Named::Ip(ip) if ip.is_loopback() || is_link_local_or_metadata(ip) => {
return Ok(route_to(named, &[ip], port));
}
Named::Name(name) if is_localhost(name) => {
let loopback = [Ipv6Addr::LOCALHOST.into(), Ipv4Addr::LOCALHOST.into()];
return Ok(route_to(named, &loopback, port));
}
Named::Ip(_) | Named::Name(_) => {}
}
let user_proxy = match proxy_for(proxies, named, port) {
Some(intercept) => Some(UserProxy::of(&intercept).map_err(io::Error::other)?),
None => None,
};
let route = match (user_proxy, named) {
(None, Named::Ip(ip)) => route_to(named, &[ip], port),
(None, Named::Name(name)) => route_to(named, &look_up(name).await?, port),
(
Some(UserProxy {
upstream,
looks_up_names: true,
}),
Named::Name(name),
) => Route::ThroughNamed {
upstream,
to: Destination {
host: Host::Name(name.to_owned()),
port,
},
},
(Some(UserProxy { upstream, .. }), Named::Ip(ip)) => Route::ThroughAt {
upstream,
addresses: vec![SocketAddr::new(ip, port)],
},
(
Some(UserProxy {
upstream,
looks_up_names: false,
}),
Named::Name(name),
) => match route_to(named, &look_up(name).await?, port) {
Route::Direct(addresses) => Route::ThroughAt {
upstream,
addresses,
},
refused => refused,
},
};
Ok(route)
}
async fn look_up(name: &str) -> io::Result<Vec<IpAddr>> {
let addresses = ssrf::resolve_host(name)
.await
.map_err(|error| io::Error::new(io::ErrorKind::NotFound, error.to_string()))?;
if addresses.is_empty() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("{name} has no addresses"),
));
}
Ok(addresses)
}
fn route_to(named: Named<'_>, addresses: &[IpAddr], port: u16) -> Route {
match addresses.iter().find(|ip| is_link_local_or_metadata(**ip)) {
Some(refused) => Route::Refused(format!(
"{named} ({refused}) is a link-local or cloud-metadata address, which the browser does not connect to"
)),
None => Route::Direct(
addresses
.iter()
.map(|ip| SocketAddr::new(*ip, port))
.collect(),
),
}
}
fn proxy_for(proxies: &Matcher, named: Named<'_>, port: u16) -> Option<Intercept> {
let host = match named {
Named::Ip(IpAddr::V6(ip)) => format!("[{ip}]"),
named => named.to_string(),
};
let schemes: &[&str] = match port {
80 => &["http"],
443 => &["https"],
_ => &["http", "https"],
};
schemes.iter().find_map(|scheme| {
let uri = format!("{scheme}://{host}:{port}/").parse().ok()?;
proxies.intercept(&uri)
})
}
struct UserProxy {
upstream: Upstream,
looks_up_names: bool,
}
impl UserProxy {
fn of(intercept: &Intercept) -> Result<Self, String> {
let uri = intercept.uri();
let address = match (uri.host(), uri.port_u16()) {
(Some(host), Some(port)) => format!("{host}:{port}"),
(Some(host), None) => match uri.scheme_str() {
Some("socks5" | "socks5h") => format!("{host}:1080"),
_ => format!("{host}:80"),
},
(None, _) => return Err(format!("the proxy {uri} names no host")),
};
if intercept.basic_auth().is_some() || intercept.raw_auth().is_some() {
return Err(format!(
"the browser cannot connect through the proxy {uri}, because its URL holds a \
user name and password: rho's browser proxy can be reached by other accounts on \
this machine, which could borrow them. Use a proxy without credentials, or add \
the hosts the browser needs to NO_PROXY"
));
}
match uri.scheme_str() {
Some("http") => Ok(Self {
upstream: Upstream::Http { address },
looks_up_names: true,
}),
Some(scheme @ ("socks5" | "socks5h")) => Ok(Self {
upstream: Upstream::Socks5 { address },
looks_up_names: scheme == "socks5h",
}),
_ => Err(format!(
"the browser cannot connect through the proxy {uri} that HTTPS_PROXY, HTTP_PROXY, \
ALL_PROXY or the system settings name: rho's browser uses http://, socks5:// and \
socks5h:// proxies only. Point that variable at one of those, or add the hosts \
the browser needs to NO_PROXY"
)),
}
}
}
pub(crate) async fn explain(host: &str, port: u16) -> String {
let destination = Destination {
host: Host::Name(host.to_owned()),
port,
};
let unexplained = "the browser could not connect to it, or to a page it redirected to";
match route(&destination, &Matcher::from_system()).await {
Ok(Route::Refused(reason)) => format!("{unexplained}; asked again, rho finds {reason}"),
Err(error) => format!("{unexplained}; asked again, {error}"),
Ok(Route::ThroughAt { upstream, .. } | Route::ThroughNamed { upstream, .. }) => format!(
"the proxy at {} did not connect to it, or to a page it redirected to",
upstream.address()
),
Ok(Route::Direct(_)) => unexplained.to_owned(),
}
}
#[cfg(test)]
#[path = "connect_tests.rs"]
mod tests;