Skip to main content

cant_proxy/
upstream.rs

1//! The user's own proxy, which the cant's proxy chains through after its own checks: an HTTP
2//! proxy (`CONNECT`, optionally with Basic credentials) or a SOCKS5 proxy (RFC 1928, optionally
3//! with a user name and password, RFC 1929), and the user's `NO_PROXY`, whose hosts are dialled
4//! directly instead. Credentials never appear in `Debug`, `Display`, log lines or errors.
5
6use std::fmt;
7use std::io::{Read, Write};
8use std::net::{IpAddr, TcpStream, ToSocketAddrs};
9use std::time::Duration;
10
11use crate::request::{self, Connect};
12
13/// How to talk to the upstream proxy.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Kind {
16    /// `http://`: `CONNECT host:port`.
17    Http,
18    /// `socks5://` or `socks5h://`: both send the host *name* (address type 3), so the SOCKS
19    /// server resolves it, as `socks5h` means. A name is never resolved here and sent as an
20    /// address: that would bypass the upstream's own name rules.
21    Socks5,
22}
23
24/// A user name and password for the upstream. `Debug` shows the user only.
25#[derive(Clone, PartialEq, Eq)]
26pub struct Auth {
27    pub user: String,
28    pub pass: String,
29}
30
31impl fmt::Debug for Auth {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        f.debug_struct("Auth")
34            .field("user", &self.user)
35            .field("pass", &"<redacted>")
36            .finish()
37    }
38}
39
40/// An upstream proxy to chain through (the user's own `HTTPS_PROXY` or `ALL_PROXY`).
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Upstream {
43    pub kind: Kind,
44    pub host: String,
45    pub port: u16,
46    pub auth: Option<Auth>,
47}
48
49/// The URL without its credentials: `scheme://host:port`.
50impl fmt::Display for Upstream {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        let scheme = match self.kind {
53            Kind::Http => "http",
54            Kind::Socks5 => "socks5h",
55        };
56        if self.host.contains(':') {
57            write!(f, "{scheme}://[{}]:{}", self.host, self.port)
58        } else {
59            write!(f, "{scheme}://{}:{}", self.host, self.port)
60        }
61    }
62}
63
64/// `url` with any password replaced by `***`, for messages about a proxy URL.
65pub fn redact(url: &str) -> String {
66    let (scheme, rest) = match url.split_once("://") {
67        Some((s, r)) => (format!("{s}://"), r),
68        None => (String::new(), url),
69    };
70    let authority_end = rest.find('/').unwrap_or(rest.len());
71    match rest[..authority_end].rfind('@') {
72        Some(at) => {
73            let user = rest[..at].split(':').next().unwrap_or("");
74            format!("{scheme}{user}:***{}", &rest[at..])
75        }
76        None => url.to_string(),
77    }
78}
79
80impl Upstream {
81    /// `http://[user:pass@]host:port` (the scheme may be left out), or
82    /// `socks5://[user:pass@]host[:port]` / `socks5h://...` (port 1080 by default). User name
83    /// and password are percent-decoded. No path; `https://` proxies aren't supported.
84    pub fn parse(url: &str) -> Result<Upstream, String> {
85        let shown = redact(url);
86        let (kind, rest) = if let Some(r) = url.strip_prefix("http://") {
87            (Kind::Http, r)
88        } else if let Some(r) = url
89            .strip_prefix("socks5h://")
90            .or_else(|| url.strip_prefix("socks5://"))
91        {
92            (Kind::Socks5, r)
93        } else if url.contains("://") {
94            return Err(format!(
95                "upstream `{shown}` must be an http://, socks5:// or socks5h:// proxy"
96            ));
97        } else {
98            (Kind::Http, url)
99        };
100        let rest = rest.strip_suffix('/').unwrap_or(rest);
101        if rest.contains('/') {
102            return Err(format!("upstream `{shown}` must be scheme://host:port"));
103        }
104        let (auth, hostport) = match rest.rsplit_once('@') {
105            Some((userinfo, hp)) => (Some(auth(userinfo, kind, &shown)?), hp),
106            None => (None, rest),
107        };
108        let (host, port) = split_host_port(hostport, kind, &shown)?;
109        Ok(Upstream {
110            kind,
111            host,
112            port,
113            auth,
114        })
115    }
116
117    /// Connects to the upstream and asks it for a tunnel to `c`. The stream is ready for the
118    /// client's bytes; errors are an HTTP status and a reason for the log.
119    pub(crate) fn open(&self, c: &Connect, timeout: Duration) -> Result<TcpStream, (u16, String)> {
120        let addrs = (self.host.as_str(), self.port)
121            .to_socket_addrs()
122            .map_err(|e| (502, format!("upstream lookup failed: {e}")))?;
123        let mut s = addrs
124            .into_iter()
125            .find_map(|a| TcpStream::connect_timeout(&a, timeout).ok())
126            .ok_or_else(|| (502, "upstream unreachable".to_string()))?;
127        let _ = s.set_read_timeout(Some(timeout));
128        match self.kind {
129            Kind::Http => self.http_connect(&mut s, c)?,
130            Kind::Socks5 => self.socks5_connect(&mut s, c).map_err(|why| (502, why))?,
131        }
132        let _ = s.set_read_timeout(None);
133        Ok(s)
134    }
135
136    fn http_connect(&self, s: &mut TcpStream, c: &Connect) -> Result<(), (u16, String)> {
137        let target = format!("{}:{}", c.host, c.port);
138        let login = self
139            .auth
140            .as_ref()
141            .map(|a| {
142                format!(
143                    "Proxy-Authorization: Basic {}\r\n",
144                    base64(format!("{}:{}", a.user, a.pass).as_bytes())
145                )
146            })
147            .unwrap_or_default();
148        // A failed write shows as the missing answer read next.
149        let _ = s.write_all(
150            format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n{login}\r\n").as_bytes(),
151        );
152        let (head, rest) =
153            request::read_head(s, 8192).map_err(|r| (502, format!("upstream: {}", r.reason)))?;
154        let status = std::str::from_utf8(&head)
155            .ok()
156            .and_then(|h| h.split(' ').nth(1))
157            .unwrap_or("");
158        match status {
159            "200" if rest.is_empty() => Ok(()),
160            "407" => Err((
161                502,
162                format!(
163                    "upstream answered 407 (proxy login {})",
164                    if self.auth.is_some() {
165                        "refused"
166                    } else {
167                        "required: put user:password@ in the proxy URL"
168                    }
169                ),
170            )),
171            _ => Err((502, format!("upstream answered {status}"))),
172        }
173    }
174
175    fn socks5_connect(&self, s: &mut TcpStream, c: &Connect) -> Result<(), String> {
176        let method = if self.auth.is_some() { 2 } else { 0 };
177        let closed = |e: std::io::Error| format!("the SOCKS proxy closed the connection ({e})");
178        let _ = s.write_all(&[5, 1, method]);
179        let mut choice = [0u8; 2];
180        s.read_exact(&mut choice).map_err(closed)?;
181        if choice[0] != 5 {
182            return Err("upstream isn't a SOCKS5 proxy".into());
183        }
184        if choice[1] != method {
185            return Err(format!(
186                "the SOCKS proxy wants another login method ({})",
187                if self.auth.is_some() {
188                    "it was given a user name and password"
189                } else {
190                    "put user:password@ in the proxy URL"
191                }
192            ));
193        }
194        if let Some(a) = &self.auth {
195            let len = |s: &str| {
196                u8::try_from(s.len()).map_err(|_| {
197                    "SOCKS5 user names and passwords are at most 255 bytes".to_string()
198                })
199            };
200            let mut m = vec![1, len(&a.user)?];
201            m.extend_from_slice(a.user.as_bytes());
202            m.push(len(&a.pass)?);
203            m.extend_from_slice(a.pass.as_bytes());
204            let _ = s.write_all(&m);
205            let mut status = [0u8; 2];
206            s.read_exact(&mut status).map_err(closed)?;
207            if status[1] != 0 {
208                return Err("the SOCKS proxy refused the user name and password".into());
209            }
210        }
211        let mut req = vec![5, 1, 0];
212        match c.ip {
213            Some(IpAddr::V4(ip)) => {
214                req.push(1);
215                req.extend_from_slice(&ip.octets());
216            }
217            Some(IpAddr::V6(ip)) => {
218                req.push(4);
219                req.extend_from_slice(&ip.octets());
220            }
221            None => {
222                // Canonical names are at most 253 bytes.
223                let n = u8::try_from(c.host.len()).map_err(|_| "name too long for SOCKS5")?;
224                req.push(3);
225                req.push(n);
226                req.extend_from_slice(c.host.as_bytes());
227            }
228        }
229        req.extend_from_slice(&c.port.to_be_bytes());
230        let _ = s.write_all(&req);
231        // The reply, read exactly: anything after it belongs to the tunnel.
232        let mut head = [0u8; 4];
233        s.read_exact(&mut head).map_err(closed)?;
234        if head[0] != 5 {
235            return Err("upstream isn't a SOCKS5 proxy".into());
236        }
237        if head[1] != 0 {
238            return Err(format!("the SOCKS proxy refused: {}", socks_reply(head[1])));
239        }
240        let addr_len = match head[3] {
241            1 => 4,
242            4 => 16,
243            3 => {
244                let mut n = [0u8; 1];
245                s.read_exact(&mut n).map_err(closed)?;
246                usize::from(n[0])
247            }
248            t => {
249                return Err(format!(
250                    "the SOCKS proxy answered an unknown address type {t}"
251                ));
252            }
253        };
254        let mut rest = vec![0u8; addr_len + 2];
255        s.read_exact(&mut rest).map_err(closed)?;
256        Ok(())
257    }
258}
259
260/// RFC 1928 §6 reply codes.
261fn socks_reply(code: u8) -> String {
262    match code {
263        1 => "general failure".into(),
264        2 => "connection not allowed by ruleset".into(),
265        3 => "network unreachable".into(),
266        4 => "host unreachable".into(),
267        5 => "connection refused".into(),
268        6 => "TTL expired".into(),
269        7 => "command not supported".into(),
270        8 => "address type not supported".into(),
271        n => format!("error {n}"),
272    }
273}
274
275fn auth(userinfo: &str, kind: Kind, shown: &str) -> Result<Auth, String> {
276    let (user, pass) = userinfo.split_once(':').unwrap_or((userinfo, ""));
277    let decode =
278        |s: &str| percent_decode(s).ok_or_else(|| format!("upstream `{shown}` has a bad %-escape"));
279    let (user, pass) = (decode(user)?, decode(pass)?);
280    if user.is_empty() {
281        return Err(format!("upstream `{shown}` has an empty user name"));
282    }
283    if kind == Kind::Socks5 && (user.len() > 255 || pass.len() > 255) {
284        return Err(format!(
285            "upstream `{shown}`: SOCKS5 user names and passwords are at most 255 bytes"
286        ));
287    }
288    Ok(Auth { user, pass })
289}
290
291fn split_host_port(hp: &str, kind: Kind, shown: &str) -> Result<(String, u16), String> {
292    let (host, port) = if let Some(v6) = hp.strip_prefix('[') {
293        let (h, after) = v6
294            .split_once(']')
295            .ok_or_else(|| format!("upstream `{shown}` has a bad [address]"))?;
296        (h, after.strip_prefix(':'))
297    } else {
298        match hp.rsplit_once(':') {
299            Some((h, p)) => (h, Some(p)),
300            None => (hp, None),
301        }
302    };
303    if host.is_empty() {
304        return Err(format!("upstream `{shown}` has no host"));
305    }
306    let port = match (port, kind) {
307        (Some(p), _) => p
308            .parse::<u16>()
309            .ok()
310            .filter(|p| *p > 0)
311            .ok_or_else(|| format!("upstream `{shown}` has a bad port"))?,
312        (None, Kind::Socks5) => 1080,
313        (None, Kind::Http) => return Err(format!("upstream `{shown}` has no port")),
314    };
315    Ok((host.to_string(), port))
316}
317
318/// `%XX` escapes to bytes; `None` for a bad escape or a result that isn't UTF-8.
319fn percent_decode(s: &str) -> Option<String> {
320    let b = s.as_bytes();
321    let mut out = Vec::with_capacity(b.len());
322    let mut i = 0;
323    while i < b.len() {
324        if b[i] == b'%' {
325            let hex = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
326            out.push(u8::from_str_radix(hex, 16).ok()?);
327            i += 3;
328        } else {
329            out.push(b[i]);
330            i += 1;
331        }
332    }
333    String::from_utf8(out).ok()
334}
335
336/// Standard base64 with padding (RFC 4648 §4), for `Proxy-Authorization: Basic`.
337fn base64(data: &[u8]) -> String {
338    const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
339    let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
340    for chunk in data.chunks(3) {
341        let n = chunk
342            .iter()
343            .enumerate()
344            .fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i)));
345        for i in 0..4 {
346            if i <= chunk.len() {
347                out.push(char::from(A[((n >> (18 - 6 * i)) & 63) as usize]));
348            } else {
349                out.push('=');
350            }
351        }
352    }
353    out
354}
355
356/// The user's `NO_PROXY`: targets matching it are dialled directly (with every check), not
357/// through the upstream. Matching follows Go's `golang.org/x/net/http/httpproxy` (which curl
358/// shares in the essentials): `*` matches everything; `name` matches the name and the names
359/// under it, `.name` only those under it; an IP matches that address, `a.b.c.d/n` a range (a
360/// name target is never resolved to match an IP entry); `:port` limits an entry to that port.
361#[derive(Debug, Clone, Default, PartialEq, Eq)]
362pub struct NoProxy {
363    all: bool,
364    entries: Vec<NoProxyEntry>,
365}
366
367#[derive(Debug, Clone, PartialEq, Eq)]
368enum Pattern {
369    /// Matches the name and below (`sub` false), or only below (`sub` true).
370    Name {
371        name: String,
372        sub: bool,
373    },
374    Net {
375        ip: IpAddr,
376        bits: u8,
377    },
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
381struct NoProxyEntry {
382    pattern: Pattern,
383    port: Option<u16>,
384}
385
386impl NoProxy {
387    /// Parses a `NO_PROXY` value; entries it can't read are skipped (as curl and Go do).
388    pub fn parse(list: &str) -> NoProxy {
389        let mut out = NoProxy::default();
390        for raw in list.split(',').map(str::trim).filter(|e| !e.is_empty()) {
391            if raw == "*" {
392                out.all = true;
393                continue;
394            }
395            if let Some(e) = entry(&raw.to_ascii_lowercase()) {
396                out.entries.push(e);
397            }
398        }
399        out
400    }
401
402    /// Whether nothing is listed.
403    pub fn is_empty(&self) -> bool {
404        !self.all && self.entries.is_empty()
405    }
406
407    /// Whether `c` goes directly.
408    pub(crate) fn matches(&self, c: &Connect) -> bool {
409        self.all
410            || self.entries.iter().any(|e| {
411                e.port.is_none_or(|p| p == c.port)
412                    && match (&e.pattern, c.ip) {
413                        (Pattern::Name { name, sub }, None) => {
414                            c.host.ends_with(&format!(".{name}")) || (!sub && c.host == *name)
415                        }
416                        (Pattern::Net { ip, bits }, Some(t)) => in_net(t, *ip, *bits),
417                        _ => false,
418                    }
419            })
420    }
421}
422
423/// One entry: `name`, `.name`, `*.name`, `ip`, `[v6]`, `ip/bits`, each with an optional
424/// `:port` (not for a bare IPv6 address, whose colons are its own).
425fn entry(raw: &str) -> Option<NoProxyEntry> {
426    if let Some((net, bits)) = raw.split_once('/') {
427        let ip: IpAddr = net.parse().ok()?;
428        let max = if ip.is_ipv4() { 32 } else { 128 };
429        let bits: u8 = bits.parse().ok().filter(|b| *b <= max)?;
430        return Some(NoProxyEntry {
431            pattern: Pattern::Net { ip, bits },
432            port: None,
433        });
434    }
435    if let Ok(ip) = raw.parse::<IpAddr>() {
436        return Some(NoProxyEntry {
437            pattern: Pattern::Net {
438                ip,
439                bits: if ip.is_ipv4() { 32 } else { 128 },
440            },
441            port: None,
442        });
443    }
444    let (host, port) = if let Some(v6) = raw.strip_prefix('[') {
445        let (h, after) = v6.split_once(']')?;
446        let port = match after {
447            "" => None,
448            _ => Some(after.strip_prefix(':')?.parse().ok()?),
449        };
450        let ip: IpAddr = h.parse().ok()?;
451        return Some(NoProxyEntry {
452            pattern: Pattern::Net { ip, bits: 128 },
453            port,
454        });
455    } else {
456        match raw.rsplit_once(':') {
457            Some((h, p)) => (h, Some(p.parse::<u16>().ok()?)),
458            None => (raw, None),
459        }
460    };
461    if let Ok(ip) = host.parse::<IpAddr>() {
462        return Some(NoProxyEntry {
463            pattern: Pattern::Net {
464                ip,
465                bits: if ip.is_ipv4() { 32 } else { 128 },
466            },
467            port,
468        });
469    }
470    let (name, sub) = match host.strip_prefix("*.").or_else(|| host.strip_prefix('.')) {
471        Some(n) => (n, true),
472        None => (host, false),
473    };
474    (!name.is_empty()).then(|| NoProxyEntry {
475        pattern: Pattern::Name {
476            name: name.to_string(),
477            sub,
478        },
479        port,
480    })
481}
482
483fn in_net(target: IpAddr, net: IpAddr, bits: u8) -> bool {
484    match (target, net) {
485        (IpAddr::V4(t), IpAddr::V4(n)) => {
486            let mask = u32::MAX.checked_shl(32 - u32::from(bits)).unwrap_or(0);
487            u32::from(t) & mask == u32::from(n) & mask
488        }
489        (IpAddr::V6(t), IpAddr::V6(n)) => {
490            let mask = u128::MAX.checked_shl(128 - u32::from(bits)).unwrap_or(0);
491            u128::from(t) & mask == u128::from(n) & mask
492        }
493        _ => false,
494    }
495}
496
497#[cfg(test)]
498mod tests;