1#![forbid(unsafe_code)]
12
13pub mod deny;
14mod request;
15
16use std::io::{Read, Write};
17use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, ToSocketAddrs};
18use std::sync::Arc;
19use std::sync::atomic::{AtomicUsize, Ordering};
20use std::time::{Duration, Instant};
21
22use cant_manifest::net::HostPort;
23
24pub use request::{Connect, Refusal};
25
26#[derive(Debug, Clone, Copy)]
28pub struct Limits {
29 pub max_tunnels: usize,
30 pub max_head: usize,
31 pub head: Duration,
32 pub dns: Duration,
33 pub connect: Duration,
34 pub idle: Duration,
35}
36
37impl Default for Limits {
38 fn default() -> Self {
39 Limits {
40 max_tunnels: 64,
41 max_head: 8192,
42 head: Duration::from_secs(10),
43 dns: Duration::from_secs(5),
44 connect: Duration::from_secs(10),
45 idle: Duration::from_secs(300),
46 }
47 }
48}
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Upstream {
53 pub host: String,
54 pub port: u16,
55}
56
57impl Upstream {
58 pub fn parse(url: &str) -> Result<Upstream, String> {
60 let rest = url.strip_prefix("http://").unwrap_or(url);
61 if url.starts_with("https://") || rest.contains("://") {
62 return Err(format!("upstream `{url}` must be an http:// proxy"));
63 }
64 let rest = rest.strip_suffix('/').unwrap_or(rest);
65 if rest.contains('@') {
66 return Err("upstream proxy credentials aren't supported".into());
67 }
68 if rest.contains('/') {
69 return Err(format!("upstream `{url}` must be http://host:port"));
70 }
71 let (host, port) = rest
72 .rsplit_once(':')
73 .ok_or_else(|| format!("upstream `{url}` has no port"))?;
74 let port = port
75 .parse::<u16>()
76 .ok()
77 .filter(|p| *p > 0)
78 .ok_or_else(|| format!("upstream `{url}` has a bad port"))?;
79 if host.is_empty() {
80 return Err(format!("upstream `{url}` has no host"));
81 }
82 Ok(Upstream {
83 host: host.to_string(),
84 port,
85 })
86 }
87}
88
89#[derive(Debug, Clone, Default)]
91pub struct Rules {
92 pub allow: Vec<HostPort>,
93 pub upstream: Option<Upstream>,
94 pub limits: Limits,
95}
96
97#[derive(Debug, Clone, PartialEq, Eq)]
100pub enum Decision {
101 Allowed {
103 target: String,
104 via: String,
105 ms: u128,
106 },
107 Refused {
109 status: u16,
110 target: String,
111 reason: String,
112 ms: u128,
113 },
114 Closed {
116 target: String,
117 up: u64,
118 down: u64,
119 ms: u128,
120 },
121}
122
123impl std::fmt::Display for Decision {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 match self {
126 Decision::Allowed { target, via, ms } => {
127 write!(f, "allow CONNECT {target} {via} ms={ms}")
128 }
129 Decision::Refused {
130 status,
131 target,
132 reason,
133 ms,
134 } => {
135 let sep = if target.is_empty() { "" } else { " " };
136 write!(f, "deny {status}{sep}{target} reason={reason} ms={ms}")
137 }
138 Decision::Closed {
139 target,
140 up,
141 down,
142 ms,
143 } => write!(f, "close {target} up={up} down={down} ms={ms}"),
144 }
145 }
146}
147
148pub type Log = Arc<dyn Fn(&Decision) + Send + Sync>;
150
151type Resolve = Arc<dyn Fn(&str, u16) -> std::io::Result<Vec<SocketAddr>> + Send + Sync>;
152type Deny = Arc<dyn Fn(IpAddr) -> Option<&'static str> + Send + Sync>;
153
154#[derive(Clone)]
156pub struct Proxy {
157 rules: Arc<Rules>,
158 log: Log,
159 resolve: Resolve,
160 deny: Deny,
161 active: Arc<AtomicUsize>,
162}
163
164impl Proxy {
165 pub fn new(rules: Rules, log: Log) -> Proxy {
168 let own = deny::own_addresses();
169 Proxy {
170 rules: Arc::new(rules),
171 log,
172 resolve: Arc::new(|host, port| (host, port).to_socket_addrs().map(Iterator::collect)),
173 deny: Arc::new(move |ip| deny::denied(ip, &own)),
174 active: Arc::new(AtomicUsize::new(0)),
175 }
176 }
177
178 pub fn serve(self, listener: TcpListener) -> std::thread::JoinHandle<()> {
180 std::thread::spawn(move || {
181 for conn in listener.incoming().flatten() {
183 let me = self.clone();
184 std::thread::spawn(move || me.handle(conn));
185 }
186 })
187 }
188
189 fn log(&self, d: Decision) {
190 (self.log)(&d);
191 }
192
193 fn handle(&self, mut client: TcpStream) {
195 let start = Instant::now();
196 let ms = || start.elapsed().as_millis();
197 let n = self.active.fetch_add(1, Ordering::SeqCst);
198 let _slot = Slot(&self.active);
199 if n >= self.rules.limits.max_tunnels {
200 return self.refuse(&mut client, 503, "", "too many tunnels", ms());
201 }
202 let _ = client.set_read_timeout(Some(self.rules.limits.head));
203 let (head, early) = match request::read_head(&mut client, self.rules.limits.max_head) {
204 Ok(h) => h,
205 Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
206 };
207 let c = match request::parse(&head) {
208 Ok(c) => c,
209 Err(r) => return self.refuse(&mut client, r.status, "", &r.reason, ms()),
210 };
211 let target = format!("{}:{}", c.host, c.port);
212 if !self.rules.allow.iter().any(|e| e.matches(&c.host, c.port)) {
214 return self.refuse(&mut client, 403, &target, "not in the allow list", ms());
215 }
216 let (upstream, via) = match &self.rules.upstream {
217 Some(up) => match self.through(up, &c) {
218 Ok(s) => (s, format!("via {}:{}", up.host, up.port)),
219 Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
220 },
221 None => match self.dial(&c) {
222 Ok((s, ip)) => (s, format!("ip={ip}")),
223 Err((status, why)) => return self.refuse(&mut client, status, &target, &why, ms()),
224 },
225 };
226 let _ = client.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n");
228 self.log(Decision::Allowed {
229 target: target.clone(),
230 via,
231 ms: ms(),
232 });
233 let (up, down) = splice(client, upstream, &early, self.rules.limits.idle);
234 self.log(Decision::Closed {
235 target,
236 up,
237 down,
238 ms: ms(),
239 });
240 }
241
242 fn refuse(&self, client: &mut TcpStream, status: u16, target: &str, why: &str, ms: u128) {
243 let text = match status {
244 400 => "Bad Request",
245 403 => "Forbidden",
246 405 => "Method Not Allowed",
247 408 => "Request Timeout",
248 431 => "Request Header Fields Too Large",
249 502 => "Bad Gateway",
250 503 => "Service Unavailable",
251 _ => "Gateway Timeout",
252 };
253 self.log(Decision::Refused {
256 status,
257 target: target.to_string(),
258 reason: why.to_string(),
259 ms,
260 });
261 let _ = client.write_all(
262 format!("HTTP/1.1 {status} {text}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
263 .as_bytes(),
264 );
265 }
266
267 fn dial(&self, c: &Connect) -> Result<(TcpStream, IpAddr), (u16, String)> {
270 let resolve = Arc::clone(&self.resolve);
271 let (host, port) = (c.host.clone(), c.port);
272 let (tx, rx) = std::sync::mpsc::channel();
273 std::thread::spawn(move || {
275 let _ = tx.send(resolve(&host, port));
276 });
277 let addrs = match rx.recv_timeout(self.rules.limits.dns) {
278 Ok(Ok(a)) if !a.is_empty() => a,
279 Ok(Ok(_)) => return Err((502, "the name has no address".into())),
280 Ok(Err(e)) => return Err((502, format!("lookup failed: {e}"))),
281 Err(_) => return Err((504, "lookup took too long".into())),
282 };
283 if let Some((ip, why)) = addrs
284 .iter()
285 .find_map(|a| (self.deny)(a.ip()).map(|w| (a.ip(), w)))
286 {
287 return Err((403, format!("resolves to {ip}: {why}")));
288 }
289 let mut last = String::new();
290 for a in &addrs {
291 match TcpStream::connect_timeout(a, self.rules.limits.connect) {
292 Ok(s) => return Ok((s, a.ip())),
293 Err(e) => last = format!("connecting to {}: {e}", a.ip()),
294 }
295 }
296 Err((502, last))
297 }
298
299 fn through(&self, up: &Upstream, c: &Connect) -> Result<TcpStream, (u16, String)> {
301 let addrs = (up.host.as_str(), up.port)
302 .to_socket_addrs()
303 .map_err(|e| (502, format!("upstream lookup failed: {e}")))?;
304 let mut s = addrs
305 .into_iter()
306 .find_map(|a| TcpStream::connect_timeout(&a, self.rules.limits.connect).ok())
307 .ok_or_else(|| (502, "upstream unreachable".to_string()))?;
308 let target = format!("{}:{}", c.host, c.port);
309 let _ =
311 s.write_all(format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes());
312 let _ = s.set_read_timeout(Some(self.rules.limits.connect));
313 let (head, rest) = request::read_head(&mut s, self.rules.limits.max_head)
314 .map_err(|r| (502, format!("upstream: {}", r.reason)))?;
315 let status = std::str::from_utf8(&head)
316 .ok()
317 .and_then(|h| h.split(' ').nth(1))
318 .unwrap_or("");
319 if status != "200" || !rest.is_empty() {
320 return Err((502, format!("upstream answered {status}")));
321 }
322 let _ = s.set_read_timeout(None);
323 Ok(s)
324 }
325
326 #[cfg(test)]
327 fn for_test(rules: Rules, log: Log, resolve: Resolve, deny: Deny) -> Proxy {
328 Proxy {
329 rules: Arc::new(rules),
330 log,
331 resolve,
332 deny,
333 active: Arc::new(AtomicUsize::new(0)),
334 }
335 }
336}
337
338impl std::fmt::Debug for Proxy {
339 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
340 f.debug_struct("Proxy")
341 .field("rules", &self.rules)
342 .field("active", &self.active.load(Ordering::SeqCst))
343 .finish_non_exhaustive()
344 }
345}
346
347struct Slot<'a>(&'a AtomicUsize);
349
350impl Drop for Slot<'_> {
351 fn drop(&mut self) {
352 self.0.fetch_sub(1, Ordering::SeqCst);
353 }
354}
355
356fn splice(client: TcpStream, server: TcpStream, early: &[u8], idle: Duration) -> (u64, u64) {
359 let _ = client.set_read_timeout(Some(idle));
360 let _ = server.set_read_timeout(Some(idle));
361 let (c, s) = (&client, &server);
362 let (up, down) = std::thread::scope(|scope| {
363 let up = scope.spawn(move || {
364 let n = copy(&mut early.chain(c), &mut { s });
365 let _ = s.shutdown(Shutdown::Write);
366 n
367 });
368 let down = copy(&mut { s }, &mut { c });
369 let _ = c.shutdown(Shutdown::Write);
370 (up.join().unwrap_or(0), down)
371 });
372 let _ = server.shutdown(Shutdown::Both);
373 let _ = client.shutdown(Shutdown::Both);
374 (up, down)
375}
376
377fn copy(from: &mut dyn Read, to: &mut dyn Write) -> u64 {
379 let mut buf = [0u8; 16 * 1024];
380 let mut n = 0u64;
381 loop {
382 match from.read(&mut buf) {
383 Ok(0) | Err(_) => return n,
384 Ok(k) => {
385 if to.write_all(&buf[..k]).is_err() {
386 return n;
387 }
388 n += k as u64;
389 }
390 }
391 }
392}
393
394#[cfg(test)]
395mod tests;