use std::{error::Error, fmt, net::SocketAddr};
use countersign_protocol::Origin;
use ipnet::IpNet;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpStream,
};
use super::{Result, config::EgressProxy, invalid};
const MAX_HEAD: usize = 8 * 1024;
#[derive(Debug)]
pub struct ProxyAnswer(pub u16);
impl fmt::Display for ProxyAnswer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "the egress proxy answered {}", self.0)
}
}
impl Error for ProxyAnswer {}
pub fn error_value(error: &(dyn Error + Send + Sync + 'static)) -> &'static str {
match error.downcast_ref::<ProxyAnswer>() {
Some(ProxyAnswer(400..=499)) => "proxy_denied",
Some(ProxyAnswer(500..=599)) => "upstream_failure",
_ => "proxy_unavailable",
}
}
pub async fn tunnel(proxy: &EgressProxy, origin: &Origin, denied: &[IpNet]) -> Result<TcpStream> {
let addresses = tokio::net::lookup_host((proxy.host.as_str(), proxy.port))
.await?
.filter(|address| {
let ip = address.ip().to_canonical();
!denied.iter().any(|block| block.contains(&ip))
})
.collect::<Vec<SocketAddr>>();
if addresses.is_empty() {
return Err(invalid("egress proxy resolved to no allowed addresses"));
}
let mut stream = TcpStream::connect(&addresses[..]).await?;
stream
.write_all(format!("CONNECT {origin} HTTP/1.1\r\nHost: {origin}\r\n\r\n").as_bytes())
.await?;
match answer(&mut stream).await? {
200..=299 => Ok(stream),
code => Err(ProxyAnswer(code).into()),
}
}
async fn answer(stream: &mut TcpStream) -> Result<u16> {
const VERSION: &[u8] = b"HTTP/1.";
let not_http = || invalid("egress proxy gave no HTTP answer");
let mut line = Vec::with_capacity(64);
let mut code = None;
for _ in 0..MAX_HEAD {
let byte = stream.read_u8().await?;
if byte != b'\n' {
line.push(byte);
if code.is_none() && !line.starts_with(VERSION) && !VERSION.starts_with(&line) {
return Err(not_http());
}
continue;
}
if line.last() == Some(&b'\r') {
line.pop();
}
match code {
None => {
let status = status(&line).ok_or_else(not_http)?;
if !(200..300).contains(&status) {
return Ok(status);
}
code = Some(status);
}
Some(status) if line.is_empty() => return Ok(status),
Some(_) => {}
}
line.clear();
}
Err(invalid("egress proxy answer exceeds the limit"))
}
fn status(line: &[u8]) -> Option<u16> {
let line = std::str::from_utf8(line).ok()?;
let mut parts = line.splitn(3, ' ');
if !matches!(parts.next()?, "HTTP/1.1" | "HTTP/1.0") {
return None;
}
let code = parts.next()?;
if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
code.parse().ok()
}