use std::io::Read;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
pub status: u16,
pub reason: String,
}
fn refuse(status: u16, reason: impl Into<String>) -> Refusal {
Refusal {
status,
reason: reason.into(),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
pub host: String,
pub port: u16,
}
pub fn read_head(r: &mut dyn Read, max: usize) -> Result<(Vec<u8>, Vec<u8>), Refusal> {
let mut buf = Vec::with_capacity(1024);
let mut chunk = [0u8; 1024];
loop {
if let Some(end) = find_end(&buf) {
let rest = buf.split_off(end);
return Ok((buf, rest));
}
if buf.len() >= max {
return Err(refuse(431, "request head too large"));
}
let n = match r.read(&mut chunk) {
Ok(0) => return Err(refuse(400, "connection closed before the request ended")),
Ok(n) => n,
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
) =>
{
return Err(refuse(408, "request head took too long"));
}
Err(e) => return Err(refuse(400, format!("reading the request: {e}"))),
};
buf.extend_from_slice(&chunk[..n]);
}
}
fn find_end(buf: &[u8]) -> Option<usize> {
let crlf = buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4);
let lf = buf.windows(2).position(|w| w == b"\n\n").map(|i| i + 2);
match (crlf, lf) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
pub fn parse(head: &[u8]) -> Result<Connect, Refusal> {
let head = std::str::from_utf8(head).map_err(|_| refuse(400, "request is not UTF-8"))?;
let line = head.split('\n').next().unwrap_or("").trim_end_matches('\r');
let parts: Vec<&str> = line.split(' ').collect();
let [method, target, version] = parts.as_slice() else {
return Err(refuse(
400,
format!("malformed request line `{}`", printable(line)),
));
};
if !matches!(*version, "HTTP/1.1" | "HTTP/1.0") {
return Err(refuse(
400,
format!("unsupported version `{}`", printable(version)),
));
}
if *method != "CONNECT" {
return Err(refuse(
405,
format!("not CONNECT: {} {}", printable(method), printable(target)),
));
}
if target.starts_with('[') {
return Err(refuse(400, "an IP address; only host names are allowed"));
}
let Some((host, port)) = target.rsplit_once(':') else {
return Err(refuse(400, format!("`{}` has no port", printable(target))));
};
let port = match port.parse::<u16>() {
Ok(p) if p > 0 && !port.starts_with('0') && port.bytes().all(|b| b.is_ascii_digit()) => p,
_ => return Err(refuse(400, format!("bad port `{}`", printable(port)))),
};
let host = host.to_ascii_lowercase();
cant_manifest::net::canonical_name(&host).map_err(|e| refuse(400, e))?;
Ok(Connect { host, port })
}
fn printable(s: &str) -> String {
s.chars()
.take(100)
.map(|c| if c.is_control() { '?' } else { c })
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn p(line: &str) -> Result<Connect, Refusal> {
parse(format!("{line}\r\nHost: x\r\n\r\n").as_bytes())
}
#[test]
fn a_plain_connect_parses() {
assert_eq!(
p("CONNECT api.github.com:443 HTTP/1.1"),
Ok(Connect {
host: "api.github.com".into(),
port: 443
})
);
assert_eq!(
p("CONNECT API.GitHub.com:8443 HTTP/1.0").expect("ok").host,
"api.github.com"
);
assert!(parse(b"CONNECT a.com:443 HTTP/1.1\n\n").is_ok());
}
#[test]
fn anything_else_is_refused_with_a_status() {
for (line, status, why) in [
(
"GET http://a.com/ HTTP/1.1",
405,
"not CONNECT: GET http://a.com/",
),
("POST https://api.agnost.ai/x HTTP/1.1", 405, "not CONNECT"),
("connect a.com:443 HTTP/1.1", 405, "not CONNECT"),
("CONNECT a.com:443 HTTP/2", 400, "unsupported version"),
("CONNECT a.com:443", 400, "malformed request line"),
("CONNECT a.com:443 HTTP/1.1", 400, "malformed request line"),
("CONNECT a.com HTTP/1.1", 400, "has no port"),
("CONNECT a.com:0 HTTP/1.1", 400, "bad port"),
("CONNECT a.com:0443 HTTP/1.1", 400, "bad port"),
("CONNECT a.com:65536 HTTP/1.1", 400, "bad port"),
("CONNECT a.com:+443 HTTP/1.1", 400, "bad port"),
("CONNECT [::1]:443 HTTP/1.1", 400, "IP address"),
(
"CONNECT 127.0.0.1:443 HTTP/1.1",
400,
"reads as an IP address",
),
(
"CONNECT 2130706433:443 HTTP/1.1",
400,
"reads as an IP address",
),
("CONNECT 0x7f.1:443 HTTP/1.1", 400, "reads as an IP address"),
("CONNECT a.com.:443 HTTP/1.1", 400, "ends with a dot"),
("CONNECT a_b.com:443 HTTP/1.1", 400, "contains `_`"),
("CONNECT a%2ecom:443 HTTP/1.1", 400, "contains `%`"),
("CONNECT user@a.com:443 HTTP/1.1", 400, "contains `@`"),
("CONNECT bücher.de:443 HTTP/1.1", 400, "contains `ü`"),
("CONNECT :443 HTTP/1.1", 400, "no host name"),
] {
let r = p(line).expect_err(line);
assert_eq!(r.status, status, "{line}: {r:?}");
assert!(r.reason.contains(why), "{line}: {r:?}");
}
let r = parse(b"CONNECT \xff:443 HTTP/1.1\r\n\r\n").expect_err("utf8");
assert_eq!(r.status, 400);
let r = p("GET \x1b[31mx HTTP/1.1").expect_err("ctl");
assert!(r.reason.contains("GET ?[31mx"), "{r:?}");
}
#[test]
fn heads_are_read_whole_and_bounded() {
let mut ok: &[u8] =
b"CONNECT a.com:443 HTTP/1.1\r\nHost: a.com:443\r\n\r\n\x16\x03\x01hello";
let (head, rest) = read_head(&mut ok, 8192).expect("head");
assert!(head.ends_with(b"\r\n\r\n"));
assert_eq!(rest, b"\x16\x03\x01hello", "bytes after the head are kept");
let big = format!(
"CONNECT a.com:443 HTTP/1.1\r\nX: {}\r\n\r\n",
"a".repeat(9000)
);
assert_eq!(
read_head(&mut big.as_bytes(), 8192)
.expect_err("big")
.status,
431
);
let mut cut: &[u8] = b"CONNECT a.com:443 HTTP/1.1\r\n";
assert_eq!(read_head(&mut cut, 8192).expect_err("eof").status, 400);
struct Slow;
impl Read for Slow {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::ErrorKind::WouldBlock.into())
}
}
assert_eq!(read_head(&mut Slow, 8192).expect_err("slow").status, 408);
struct Broken;
impl Read for Broken {
fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::ErrorKind::ConnectionReset.into())
}
}
assert_eq!(read_head(&mut Broken, 8192).expect_err("reset").status, 400);
assert_eq!(find_end(b"a\n\nb\r\n\r\n"), Some(3));
}
proptest::proptest! {
#[test]
fn parsing_never_panics(bytes in proptest::collection::vec(proptest::num::u8::ANY, 0..200)) {
let _ = parse(&bytes);
let _ = read_head(&mut bytes.as_slice(), 64);
}
#[test]
fn proxy_and_manifest_agree_on_names(labels in proptest::collection::vec("[a-z]([a-z0-9-]{0,6}[a-z0-9])?", 1..4), port in 1u16..) {
let name = labels.join(".");
let manifest = cant_manifest::net::HostPort::parse(&format!("{name}:{port}"));
let proxy = p(&format!("CONNECT {name}:{port} HTTP/1.1"));
proptest::prop_assert_eq!(manifest.is_ok(), proxy.is_ok(), "{}", name);
if let (Ok(m), Ok(c)) = (manifest, proxy) {
proptest::prop_assert!(m.matches(&c.host, c.port));
}
}
}
}