#![forbid(unsafe_code)]
pub mod deny;
mod request;
use std::io::{Read, Write};
use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use cant_manifest::net::{HostPort, UserHost};
pub use request::{Connect, Refusal};
#[derive(Debug, Clone, Copy)]
pub struct Limits {
pub max_tunnels: usize,
pub max_head: usize,
pub head: Duration,
pub dns: Duration,
pub connect: Duration,
pub idle: Duration,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_tunnels: 64,
max_head: 8192,
head: Duration::from_secs(10),
dns: Duration::from_secs(5),
connect: Duration::from_secs(10),
idle: Duration::from_secs(300),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Upstream {
pub host: String,
pub port: u16,
}
impl Upstream {
pub fn parse(url: &str) -> Result<Upstream, String> {
let rest = url.strip_prefix("http://").unwrap_or(url);
if url.starts_with("https://") || rest.contains("://") {
return Err(format!("upstream `{url}` must be an http:// proxy"));
}
let rest = rest.strip_suffix('/').unwrap_or(rest);
if rest.contains('@') {
return Err("upstream proxy credentials aren't supported".into());
}
if rest.contains('/') {
return Err(format!("upstream `{url}` must be http://host:port"));
}
let (host, port) = rest
.rsplit_once(':')
.ok_or_else(|| format!("upstream `{url}` has no port"))?;
let port = port
.parse::<u16>()
.ok()
.filter(|p| *p > 0)
.ok_or_else(|| format!("upstream `{url}` has a bad port"))?;
if host.is_empty() {
return Err(format!("upstream `{url}` has no host"));
}
Ok(Upstream {
host: host.to_string(),
port,
})
}
}
#[derive(Debug, Clone, Default)]
pub struct Rules {
pub allow: Vec<HostPort>,
pub user: Vec<UserHost>,
pub loopback: bool,
pub upstream: Option<Upstream>,
pub limits: Limits,
}
impl Rules {
fn user_named(&self, c: &Connect) -> bool {
self.user.iter().any(|u| match c.ip {
Some(ip) => u.matches_ip(ip, c.port),
None => u.matches_name(&c.host, c.port),
})
}
fn listed(&self, c: &Connect) -> bool {
c.ip.is_none() && self.allow.iter().any(|e| e.matches(&c.host, c.port))
}
fn user_may(&self, d: deny::Denial) -> bool {
match d.class {
deny::Class::Private => true,
deny::Class::Loopback | deny::Class::Own => self.loopback,
deny::Class::Other => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
Allowed {
target: String,
via: String,
ms: u128,
},
Refused {
status: u16,
target: String,
reason: String,
ms: u128,
},
Closed {
target: String,
up: u64,
down: u64,
ms: u128,
},
}
impl std::fmt::Display for Decision {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Decision::Allowed { target, via, ms } => {
write!(f, "allow CONNECT {target} {via} ms={ms}")
}
Decision::Refused {
status,
target,
reason,
ms,
} => {
let sep = if target.is_empty() { "" } else { " " };
write!(f, "deny {status}{sep}{target} reason={reason} ms={ms}")
}
Decision::Closed {
target,
up,
down,
ms,
} => write!(f, "close {target} up={up} down={down} ms={ms}"),
}
}
}
pub type Log = Arc<dyn Fn(&Decision) + Send + Sync>;
type Resolve = Arc<dyn Fn(&str, u16) -> std::io::Result<Vec<SocketAddr>> + Send + Sync>;
type Deny = Arc<dyn Fn(IpAddr) -> Option<deny::Denial> + Send + Sync>;
#[derive(Clone)]
pub struct Proxy {
rules: Arc<Rules>,
log: Log,
resolve: Resolve,
deny: Deny,
active: Arc<AtomicUsize>,
}
impl Proxy {
pub fn new(rules: Rules, log: Log) -> Proxy {
let own = deny::own_addresses();
Proxy {
rules: Arc::new(rules),
log,
resolve: Arc::new(|host, port| (host, port).to_socket_addrs().map(Iterator::collect)),
deny: Arc::new(move |ip| deny::denied(ip, &own)),
active: Arc::new(AtomicUsize::new(0)),
}
}
pub fn serve(self, listener: TcpListener) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
for conn in listener.incoming().flatten() {
let me = self.clone();
std::thread::spawn(move || me.handle(conn));
}
})
}
fn log(&self, d: Decision) {
(self.log)(&d);
}
fn handle(&self, mut client: TcpStream) {
let start = Instant::now();
let ms = || start.elapsed().as_millis();
let n = self.active.fetch_add(1, Ordering::SeqCst);
let _slot = Slot(&self.active);
if n >= self.rules.limits.max_tunnels {
return self.refuse(&mut client, 503, "", "too many tunnels", ms());
}
let _ = client.set_read_timeout(Some(self.rules.limits.head));
let (head, early) = match request::read_head(&mut client, self.rules.limits.max_head) {
Ok(h) => h,
Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
};
let c = match request::parse(&head) {
Ok(c) => c,
Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
};
let target = format!("{}:{}", c.host, c.port);
let user = self.rules.user_named(&c);
if !user && !self.rules.listed(&c) {
return self.refuse(&mut client, 403, &target, "not in the allow list", ms());
}
let (upstream, via) = match &self.rules.upstream {
Some(up) => match self.through(up, &c) {
Ok(s) => (s, format!("via {}:{}", up.host, up.port)),
Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
},
None => match self.dial(&c, user) {
Ok((s, ip)) => (s, format!("ip={ip}")),
Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
},
};
let _ = client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
self.log(Decision::Allowed {
target: target.clone(),
via,
ms: ms(),
});
let (up, down) = splice(client, upstream, &early, self.rules.limits.idle);
self.log(Decision::Closed {
target,
up,
down,
ms: ms(),
});
}
fn refuse(&self, client: &mut TcpStream, status: u16, target: &str, why: &str, ms: u128) {
let text = match status {
400 => "Bad Request",
403 => "Forbidden",
405 => "Method Not Allowed",
408 => "Request Timeout",
431 => "Request Header Fields Too Large",
502 => "Bad Gateway",
503 => "Service Unavailable",
_ => "Gateway Timeout",
};
self.log(Decision::Refused {
status,
target: target.to_string(),
reason: why.to_string(),
ms,
});
let _ = client.write_all(
format!("HTTP/1.1 {status} {text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
.as_bytes(),
);
}
fn dial(&self, c: &Connect, user: bool) -> Result<(TcpStream, IpAddr), (u16, String)> {
let addrs = match c.ip {
Some(ip) => vec![SocketAddr::new(ip, c.port)],
None => self.lookup(c)?,
};
if let Some((ip, d)) = addrs.iter().find_map(|a| {
(self.deny)(a.ip())
.filter(|d| !(user && self.rules.user_may(*d)))
.map(|d| (a.ip(), d))
}) {
let hint = if user && matches!(d.class, deny::Class::Loopback | deny::Class::Own) {
"; cant run --allow-loopback allows it"
} else {
""
};
let what = match c.ip {
Some(_) => format!("{ip}"),
None => format!("resolves to {ip}"),
};
return Err((403, format!("{what}: {}{hint}", d.why)));
}
let mut last = String::new();
for a in &addrs {
match TcpStream::connect_timeout(a, self.rules.limits.connect) {
Ok(s) => return Ok((s, a.ip())),
Err(e) => last = format!("connecting to {}: {e}", a.ip()),
}
}
Err((502, last))
}
fn lookup(&self, c: &Connect) -> Result<Vec<SocketAddr>, (u16, String)> {
let resolve = Arc::clone(&self.resolve);
let (host, port) = (c.host.clone(), c.port);
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(resolve(&host, port));
});
match rx.recv_timeout(self.rules.limits.dns) {
Ok(Ok(a)) if !a.is_empty() => Ok(a),
Ok(Ok(_)) => Err((502, "the name has no address".into())),
Ok(Err(e)) => Err((502, format!("lookup failed: {e}"))),
Err(_) => Err((504, "lookup took too long".into())),
}
}
fn through(&self, up: &Upstream, c: &Connect) -> Result<TcpStream, (u16, String)> {
let addrs = (up.host.as_str(), up.port)
.to_socket_addrs()
.map_err(|e| (502, format!("upstream lookup failed: {e}")))?;
let mut s = addrs
.into_iter()
.find_map(|a| TcpStream::connect_timeout(&a, self.rules.limits.connect).ok())
.ok_or_else(|| (502, "upstream unreachable".to_string()))?;
let target = format!("{}:{}", c.host, c.port);
let _ =
s.write_all(format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes());
let _ = s.set_read_timeout(Some(self.rules.limits.connect));
let (head, rest) = request::read_head(&mut s, self.rules.limits.max_head)
.map_err(|r| (502, format!("upstream: {}", r.reason)))?;
let status = std::str::from_utf8(&head)
.ok()
.and_then(|h| h.split(' ').nth(1))
.unwrap_or("");
if status != "200" || !rest.is_empty() {
return Err((502, format!("upstream answered {status}")));
}
let _ = s.set_read_timeout(None);
Ok(s)
}
#[cfg(test)]
fn for_test(rules: Rules, log: Log, resolve: Resolve, deny: Deny) -> Proxy {
Proxy {
rules: Arc::new(rules),
log,
resolve,
deny,
active: Arc::new(AtomicUsize::new(0)),
}
}
}
impl std::fmt::Debug for Proxy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Proxy")
.field("rules", &self.rules)
.field("active", &self.active.load(Ordering::SeqCst))
.finish_non_exhaustive()
}
}
struct Slot<'a>(&'a AtomicUsize);
impl Drop for Slot<'_> {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::SeqCst);
}
}
fn splice(client: TcpStream, server: TcpStream, early: &[u8], idle: Duration) -> (u64, u64) {
let _ = client.set_read_timeout(Some(idle));
let _ = server.set_read_timeout(Some(idle));
let (c, s) = (&client, &server);
let (up, down) = std::thread::scope(|scope| {
let up = scope.spawn(move || {
let n = copy(&mut early.chain(c), &mut { s });
let _ = s.shutdown(Shutdown::Write);
n
});
let down = copy(&mut { s }, &mut { c });
let _ = c.shutdown(Shutdown::Write);
(up.join().unwrap_or(0), down)
});
let _ = server.shutdown(Shutdown::Both);
let _ = client.shutdown(Shutdown::Both);
(up, down)
}
fn copy(from: &mut dyn Read, to: &mut dyn Write) -> u64 {
let mut buf = [0u8; 16 * 1024];
let mut n = 0u64;
loop {
match from.read(&mut buf) {
Ok(0) | Err(_) => return n,
Ok(k) => {
if to.write_all(&buf[..k]).is_err() {
return n;
}
n += k as u64;
}
}
}
}
#[cfg(test)]
mod tests;