1use std::io::Read;
6
7#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Refusal {
10 pub status: u16,
11 pub reason: String,
12}
13
14fn refuse(status: u16, reason: impl Into<String>) -> Refusal {
15 Refusal {
16 status,
17 reason: reason.into(),
18 }
19}
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Connect {
24 pub host: String,
26 pub port: u16,
27 pub ip: Option<std::net::IpAddr>,
29}
30
31pub fn read_head(r: &mut dyn Read, max: usize) -> Result<(Vec<u8>, Vec<u8>), Refusal> {
34 let mut buf = Vec::with_capacity(1024);
35 let mut chunk = [0u8; 1024];
36 loop {
37 if let Some(end) = find_end(&buf) {
38 let rest = buf.split_off(end);
39 return Ok((buf, rest));
40 }
41 if buf.len() >= max {
42 return Err(refuse(431, "request head too large"));
43 }
44 let n = match r.read(&mut chunk) {
45 Ok(0) => return Err(refuse(400, "connection closed before the request ended")),
46 Ok(n) => n,
47 Err(e)
48 if matches!(
49 e.kind(),
50 std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
51 ) =>
52 {
53 return Err(refuse(408, "request head took too long"));
54 }
55 Err(e) => return Err(refuse(400, format!("reading the request: {e}"))),
56 };
57 buf.extend_from_slice(&chunk[..n]);
58 }
59}
60
61fn find_end(buf: &[u8]) -> Option<usize> {
63 let crlf = buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4);
64 let lf = buf.windows(2).position(|w| w == b"\n\n").map(|i| i + 2);
65 match (crlf, lf) {
66 (Some(a), Some(b)) => Some(a.min(b)),
67 (a, b) => a.or(b),
68 }
69}
70
71pub fn parse(head: &[u8]) -> Result<Connect, Refusal> {
74 let head = std::str::from_utf8(head).map_err(|_| refuse(400, "request is not UTF-8"))?;
75 let line = head.split('\n').next().unwrap_or("").trim_end_matches('\r');
76 let parts: Vec<&str> = line.split(' ').collect();
77 let [method, target, version] = parts.as_slice() else {
78 return Err(refuse(
79 400,
80 format!("malformed request line `{}`", printable(line)),
81 ));
82 };
83 if !matches!(*version, "HTTP/1.1" | "HTTP/1.0") {
84 return Err(refuse(
85 400,
86 format!("unsupported version `{}`", printable(version)),
87 ));
88 }
89 if *method != "CONNECT" {
90 return Err(refuse(
92 405,
93 format!("not CONNECT: {} {}", printable(method), printable(target)),
94 ));
95 }
96 let Some((host, port)) = target.rsplit_once(':') else {
97 return Err(refuse(400, format!("`{}` has no port", printable(target))));
98 };
99 let port = match port.parse::<u16>() {
100 Ok(p) if p > 0 && !port.starts_with('0') && port.bytes().all(|b| b.is_ascii_digit()) => p,
101 _ => return Err(refuse(400, format!("bad port `{}`", printable(port)))),
102 };
103 if let Some(inner) = host.strip_prefix('[') {
106 let ip = inner
107 .strip_suffix(']')
108 .and_then(|a| a.parse::<std::net::Ipv6Addr>().ok())
109 .ok_or_else(|| refuse(400, format!("bad IPv6 address `{}`", printable(host))))?;
110 return Ok(Connect {
111 host: format!("[{ip}]"),
112 port,
113 ip: Some(ip.into()),
114 });
115 }
116 if let Ok(ip) = host.parse::<std::net::Ipv4Addr>() {
117 return Ok(Connect {
118 host: ip.to_string(),
119 port,
120 ip: Some(ip.into()),
121 });
122 }
123 let host = host.to_ascii_lowercase();
124 cant_manifest::net::canonical_name(&host).map_err(|e| refuse(400, e))?;
125 Ok(Connect {
126 host,
127 port,
128 ip: None,
129 })
130}
131
132fn printable(s: &str) -> String {
134 s.chars()
135 .take(100)
136 .map(|c| if c.is_control() { '?' } else { c })
137 .collect()
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 fn p(line: &str) -> Result<Connect, Refusal> {
145 parse(format!("{line}\r\nHost: x\r\n\r\n").as_bytes())
146 }
147
148 #[test]
149 fn a_plain_connect_parses() {
150 assert_eq!(
151 p("CONNECT api.github.com:443 HTTP/1.1"),
152 Ok(Connect {
153 host: "api.github.com".into(),
154 port: 443,
155 ip: None
156 })
157 );
158 assert_eq!(
160 p("CONNECT API.GitHub.com:8443 HTTP/1.0").expect("ok").host,
161 "api.github.com"
162 );
163 assert!(parse(b"CONNECT a.com:443 HTTP/1.1\n\n").is_ok());
164 let v4 = p("CONNECT 10.0.0.5:6443 HTTP/1.1").expect("v4");
166 assert_eq!(
167 (v4.host.as_str(), v4.ip),
168 ("10.0.0.5", Some("10.0.0.5".parse().expect("ip")))
169 );
170 let v6 = p("CONNECT [FD00::1]:443 HTTP/1.1").expect("v6");
171 assert_eq!(
172 (v6.host.as_str(), v6.ip),
173 ("[fd00::1]", Some("fd00::1".parse().expect("ip")))
174 );
175 }
176
177 #[test]
178 fn anything_else_is_refused_with_a_status() {
179 for (line, status, why) in [
180 (
181 "GET http://a.com/ HTTP/1.1",
182 405,
183 "not CONNECT: GET http://a.com/",
184 ),
185 ("POST https://api.agnost.ai/x HTTP/1.1", 405, "not CONNECT"),
186 ("connect a.com:443 HTTP/1.1", 405, "not CONNECT"),
187 ("CONNECT a.com:443 HTTP/2", 400, "unsupported version"),
188 ("CONNECT a.com:443", 400, "malformed request line"),
189 ("CONNECT a.com:443 HTTP/1.1", 400, "malformed request line"),
190 ("CONNECT a.com HTTP/1.1", 400, "has no port"),
191 ("CONNECT a.com:0 HTTP/1.1", 400, "bad port"),
192 ("CONNECT a.com:0443 HTTP/1.1", 400, "bad port"),
193 ("CONNECT a.com:65536 HTTP/1.1", 400, "bad port"),
194 ("CONNECT a.com:+443 HTTP/1.1", 400, "bad port"),
195 (
196 "CONNECT 2130706433:443 HTTP/1.1",
197 400,
198 "reads as an IP address",
199 ),
200 ("CONNECT 0x7f.1:443 HTTP/1.1", 400, "reads as an IP address"),
201 ("CONNECT 127.1:443 HTTP/1.1", 400, "reads as an IP address"),
202 (
203 "CONNECT 01.2.3.4:443 HTTP/1.1",
204 400,
205 "reads as an IP address",
206 ),
207 ("CONNECT [::1:443 HTTP/1.1", 400, "bad IPv6 address"),
208 (
209 "CONNECT [fe80::1%eth0]:443 HTTP/1.1",
210 400,
211 "bad IPv6 address",
212 ),
213 ("CONNECT a.com.:443 HTTP/1.1", 400, "ends with a dot"),
214 ("CONNECT a_b.com:443 HTTP/1.1", 400, "contains `_`"),
215 ("CONNECT a%2ecom:443 HTTP/1.1", 400, "contains `%`"),
216 ("CONNECT user@a.com:443 HTTP/1.1", 400, "contains `@`"),
217 ("CONNECT bücher.de:443 HTTP/1.1", 400, "contains `ü`"),
218 ("CONNECT :443 HTTP/1.1", 400, "no host name"),
219 ] {
220 let r = p(line).expect_err(line);
221 assert_eq!(r.status, status, "{line}: {r:?}");
222 assert!(r.reason.contains(why), "{line}: {r:?}");
223 }
224 let r = parse(b"CONNECT \xff:443 HTTP/1.1\r\n\r\n").expect_err("utf8");
225 assert_eq!(r.status, 400);
226 let r = p("GET \x1b[31mx HTTP/1.1").expect_err("ctl");
228 assert!(r.reason.contains("GET ?[31mx"), "{r:?}");
229 }
230
231 #[test]
232 fn heads_are_read_whole_and_bounded() {
233 let mut ok: &[u8] =
234 b"CONNECT a.com:443 HTTP/1.1\r\nHost: a.com:443\r\n\r\n\x16\x03\x01hello";
235 let (head, rest) = read_head(&mut ok, 8192).expect("head");
236 assert!(head.ends_with(b"\r\n\r\n"));
237 assert_eq!(rest, b"\x16\x03\x01hello", "bytes after the head are kept");
238 let big = format!(
239 "CONNECT a.com:443 HTTP/1.1\r\nX: {}\r\n\r\n",
240 "a".repeat(9000)
241 );
242 assert_eq!(
243 read_head(&mut big.as_bytes(), 8192)
244 .expect_err("big")
245 .status,
246 431
247 );
248 let mut cut: &[u8] = b"CONNECT a.com:443 HTTP/1.1\r\n";
249 assert_eq!(read_head(&mut cut, 8192).expect_err("eof").status, 400);
250 struct Slow;
251 impl Read for Slow {
252 fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
253 Err(std::io::ErrorKind::WouldBlock.into())
254 }
255 }
256 assert_eq!(read_head(&mut Slow, 8192).expect_err("slow").status, 408);
257 struct Broken;
258 impl Read for Broken {
259 fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
260 Err(std::io::ErrorKind::ConnectionReset.into())
261 }
262 }
263 assert_eq!(read_head(&mut Broken, 8192).expect_err("reset").status, 400);
264 assert_eq!(find_end(b"a\n\nb\r\n\r\n"), Some(3));
265 }
266
267 proptest::proptest! {
268 #[test]
269 fn parsing_never_panics(bytes in proptest::collection::vec(proptest::num::u8::ANY, 0..200)) {
270 let _ = parse(&bytes);
271 let _ = read_head(&mut bytes.as_slice(), 64);
272 }
273
274 #[test]
275 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..) {
276 let name = labels.join(".");
277 let manifest = cant_manifest::net::HostPort::parse(&format!("{name}:{port}"));
278 let proxy = p(&format!("CONNECT {name}:{port} HTTP/1.1"));
279 proptest::prop_assert_eq!(manifest.is_ok(), proxy.is_ok(), "{}", name);
280 if let (Ok(m), Ok(c)) = (manifest, proxy) {
281 proptest::prop_assert!(m.matches(&c.host, c.port));
282 }
283 }
284 }
285}