Skip to main content

netio/
proxy.rs

1// proxy -- which HTTP proxy a request goes through (Client::with_proxy)
2//
3//   Proxy::new("http://user:pw@proxy.lan:3128")   one proxy for http and https
4//   Proxy::none().http(..).https(..)               a proxy per scheme (Endpoint::parse)
5//   proxy.no_proxy("localhost, .corp.example, 10.0.0.0/8")
6//   Proxy::from_env()    http_proxy (lower case only), https_proxy / HTTPS_PROXY, all_proxy /
7//                        ALL_PROXY, no_proxy / NO_PROXY -- as curl reads them: HTTP_PROXY in
8//                        upper case is left alone, since a CGI program gets the request's
9//                        "Proxy:" header as that variable (httpoxy, CVE-2016-5385 and others)
10//   proxy.for_url(&url) -> Option<&Endpoint>
11//
12// http:// goes to the proxy as an absolute-form request (RFC 9112 3.2.2); https:// through a
13// CONNECT tunnel (RFC 9110 9.3.6), in which TLS checks the server itself, not the proxy.  Only
14// plain-HTTP proxies: an https:// or socks proxy URL is refused (None).  Loopback addresses and
15// localhost never go through a proxy (as Go's net/http): a local service is not sent elsewhere.
16// NO_PROXY: "*" for all, names (a leading "." or "*." optional) for themselves and the names
17// below them, IP addresses and CIDR ranges for URLs that name an address (no lookup); an entry
18// may end in ":port".
19
20use alloc::format;
21use alloc::string::String;
22use alloc::vec::Vec;
23
24use plat::net::IpAddr;
25
26use crate::url::{percent_decode, Url};
27
28/// a proxy server: where to connect and the credentials it gets (Basic)
29#[derive(Clone, PartialEq, Eq)]
30pub struct Endpoint {
31    pub host: String,
32    pub port: u16,
33    /// the Proxy-Authorization header's value ("Basic ..."), when the URL had user:password
34    auth: Option<String>,
35}
36
37impl core::fmt::Debug for Endpoint {
38    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
39        // the credentials stay out of logs
40        write!(f, "Endpoint({}:{}{})", self.host, self.port, if self.auth.is_some() { ", with credentials" } else { "" })
41    }
42}
43
44impl Endpoint {
45    /// "http://[user[:password]@]host[:port][/]" or "host[:port]" (http assumed); the port
46    /// defaults to 80.  None for another scheme (https://, socks5://), a path, or a bad host
47    pub fn parse(s: &str) -> Option<Endpoint> {
48        let s = s.trim();
49        let rest = match s.split_once("://") {
50            Some((scheme, rest)) if scheme.eq_ignore_ascii_case("http") => rest,
51            Some(_) => return None,
52            None => s,
53        };
54        let rest = rest.strip_suffix('/').unwrap_or(rest);
55        if rest.contains(['/', '?', '#']) {
56            return None;
57        }
58        let (userinfo, hostport) = match rest.rsplit_once('@') {
59            Some((u, h)) => (Some(u), h),
60            None => (None, rest),
61        };
62        let u = Url::parse(&format!("http://{}/", hostport))?;
63        let auth = userinfo.map(|ui| {
64            let (user, pw) = ui.split_once(':').unwrap_or((ui, ""));
65            let plain = format!("{}:{}", percent_decode(user, false), percent_decode(pw, false));
66            format!("Basic {}", crate::smtp::b64(plain.as_bytes()))
67        });
68        Some(Endpoint { host: u.host, port: u.port, auth })
69    }
70
71    /// with these credentials (Basic: "user:password" in base64)
72    pub fn with_auth(mut self, user: &str, password: &str) -> Endpoint {
73        self.auth = Some(format!("Basic {}", crate::smtp::b64(format!("{}:{}", user, password).as_bytes())));
74        self
75    }
76
77    /// the Proxy-Authorization header's value
78    pub fn authorization(&self) -> Option<&str> {
79        self.auth.as_deref()
80    }
81
82    /// the proxy as a URL of its own (where the client connects)
83    pub fn url(&self) -> Url {
84        Url { scheme: String::from("http"), host: self.host.clone(), port: self.port, target: String::from("/") }
85    }
86
87    /// "host:port"
88    pub fn key(&self) -> String {
89        self.url().authority()
90    }
91}
92
93#[derive(Clone, Debug, PartialEq, Eq)]
94enum NoProxy {
95    All,
96    /// a name and the names below it; the port when the entry gave one
97    Name(String, Option<u16>),
98    /// an address range (an address alone: the full length)
99    Net(IpAddr, u8, Option<u16>),
100}
101
102fn cidr_match(a: &IpAddr, net: &IpAddr, bits: u8) -> bool {
103    let (x, y): (&[u8], &[u8]) = match (a, net) {
104        (IpAddr::V4(x), IpAddr::V4(y)) => (x, y),
105        (IpAddr::V6(x), IpAddr::V6(y)) => (x, y),
106        _ => return false,
107    };
108    let full = bits as usize / 8;
109    if x[..full] != y[..full] {
110        return false;
111    }
112    let rest = bits % 8;
113    rest == 0 || (x[full] ^ y[full]) >> (8 - rest) == 0
114}
115
116fn no_proxy_entry(e: &str) -> Option<NoProxy> {
117    let e = e.trim().to_ascii_lowercase();
118    if e.is_empty() {
119        return None;
120    }
121    if e == "*" {
122        return Some(NoProxy::All);
123    }
124    // "[v6]:port", "name:port", "v4:port"; a bare v6 address has colons of its own
125    let (body, port) = if let Some(r) = e.strip_prefix('[') {
126        let (h, p) = r.split_once(']')?;
127        // nothing after the bracket, or ":port" (anything else drops the entry)
128        (String::from(h), if p.is_empty() { None } else { Some(p.strip_prefix(':')?.parse().ok()?) })
129    } else if e.matches(':').count() == 1 {
130        let (h, p) = e.split_once(':')?;
131        (String::from(h), Some(p.parse().ok()?))
132    } else {
133        (e.clone(), None)
134    };
135    let (addr, bits) = match body.split_once('/') {
136        Some((a, b)) => (a, Some(b.parse::<u8>().ok()?)),
137        None => (body.as_str(), None),
138    };
139    if let Some(ip) = IpAddr::parse(addr) {
140        let max = if matches!(ip, IpAddr::V4(_)) { 32 } else { 128 };
141        let bits = bits.unwrap_or(max);
142        return (bits <= max).then_some(NoProxy::Net(ip, bits, port));
143    }
144    if bits.is_some() {
145        return None;
146    }
147    let name = body.trim_start_matches("*.").trim_start_matches('.').trim_end_matches('.');
148    (!name.is_empty()).then(|| NoProxy::Name(String::from(name), port))
149}
150
151/// the proxies of a client: one per scheme, and the hosts that go direct
152#[derive(Clone, Debug, Default, PartialEq, Eq)]
153pub struct Proxy {
154    http: Option<Endpoint>,
155    https: Option<Endpoint>,
156    no: Vec<NoProxy>,
157}
158
159impl Proxy {
160    /// no proxy (to add them one by one)
161    pub fn none() -> Proxy {
162        Proxy::default()
163    }
164
165    /// one proxy for http and https (Endpoint::parse) -> None when it is not one
166    pub fn new(url: &str) -> Option<Proxy> {
167        let e = Endpoint::parse(url)?;
168        Some(Proxy { http: Some(e.clone()), https: Some(e), no: Vec::new() })
169    }
170
171    /// the proxy for http:// URLs
172    pub fn http(mut self, e: Endpoint) -> Proxy {
173        self.http = Some(e);
174        self
175    }
176
177    /// the proxy for https:// URLs (a CONNECT tunnel)
178    pub fn https(mut self, e: Endpoint) -> Proxy {
179        self.https = Some(e);
180        self
181    }
182
183    /// hosts that go direct: a comma-separated list as NO_PROXY writes it (entries that are not
184    /// one are left out)
185    pub fn no_proxy(mut self, list: &str) -> Proxy {
186        self.no.extend(list.split(',').filter_map(no_proxy_entry));
187        self
188    }
189
190    /// the proxies the environment names (see the module header); None when it names none
191    pub fn from_env() -> Option<Proxy> {
192        Proxy::from_vars(&|name| plat::env(name))
193    }
194
195    /// from_env with the variables from `get` (tests, or a configuration of the app's own)
196    pub fn from_vars(get: &dyn Fn(&str) -> Option<String>) -> Option<Proxy> {
197        let var = |names: &[&str]| names.iter().find_map(|n| get(n).filter(|v| !v.trim().is_empty()));
198        let all = var(&["all_proxy", "ALL_PROXY"]).and_then(|v| Endpoint::parse(&v));
199        // http_proxy in lower case only (httpoxy)
200        let http = var(&["http_proxy"]).and_then(|v| Endpoint::parse(&v)).or_else(|| all.clone());
201        let https = var(&["https_proxy", "HTTPS_PROXY"]).and_then(|v| Endpoint::parse(&v)).or(all);
202        if http.is_none() && https.is_none() {
203            return None;
204        }
205        let p = Proxy { http, https, no: Vec::new() };
206        Some(match var(&["no_proxy", "NO_PROXY"]) {
207            Some(list) => p.no_proxy(&list),
208            None => p,
209        })
210    }
211
212    /// whether a URL goes direct: loopback, localhost, or an entry of no_proxy
213    pub fn bypass(&self, url: &Url) -> bool {
214        let host = url.host.trim_end_matches('.');
215        let ip = IpAddr::parse(host.split('%').next().unwrap_or(host));
216        if ip.is_some_and(|a| a.is_loopback()) || host == "localhost" || host.ends_with(".localhost") {
217            return true;
218        }
219        self.no.iter().any(|n| match n {
220            NoProxy::All => true,
221            NoProxy::Name(name, port) => {
222                port.is_none_or(|p| p == url.port) && (host == name || (host.len() > name.len() && host.ends_with(name.as_str()) && host.as_bytes()[host.len() - name.len() - 1] == b'.'))
223            }
224            NoProxy::Net(net, bits, port) => port.is_none_or(|p| p == url.port) && ip.is_some_and(|a| cidr_match(&a, net, *bits)),
225        })
226    }
227
228    /// the proxy a request to `url` goes through (None: direct)
229    pub fn for_url(&self, url: &Url) -> Option<&Endpoint> {
230        if self.bypass(url) {
231            return None;
232        }
233        if url.is_https() { self.https.as_ref() } else { self.http.as_ref() }
234    }
235}