Skip to main content

trillium_client/proxy/
env.rs

1use super::{NoProxy, Proxy, ProxySchemes, invalid};
2use std::{fmt, io};
3
4impl Proxy {
5    /// The proxies configured by a snapshot of the process environment, as a list to install
6    /// with [`Client::with_proxy`](crate::Client::with_proxy).
7    ///
8    /// Reads `http_proxy`/`HTTP_PROXY`, `https_proxy`/`HTTPS_PROXY`, `all_proxy`/`ALL_PROXY`, and
9    /// `no_proxy`/`NO_PROXY`. Lowercase variables take precedence, including when empty. A missing
10    /// or empty per-scheme proxy uses the all-proxy fallback. Uppercase `HTTP_PROXY` is ignored
11    /// when `REQUEST_METHOD` is set: CGI, which always sets `REQUEST_METHOD`, passes a request's
12    /// `Proxy` header to the program as `HTTP_PROXY`.
13    ///
14    /// The result is what the equivalent code would build: a [`Proxy::new`] for each configured
15    /// endpoint, narrowed with [`Proxy::with_schemes`] to the scheme it serves (or left carrying
16    /// both when only the all-proxy fallback is set), with the `no_proxy` list added to each
17    /// through [`Proxy::except`]. An environment that configures no proxy produces an empty list,
18    /// which connects directly, and so does a `no_proxy` entry of `*`, without reading the proxy
19    /// variables it overrides.
20    ///
21    /// The all-proxy fallback is only read when a scheme actually falls back to it, so an
22    /// unusable `all_proxy` alongside usable per-scheme proxies is not an error. Ordinary client
23    /// construction does not read these variables, and this method does not read certificate
24    /// environment variables or change TLS trust.
25    ///
26    /// # Errors
27    ///
28    /// Returns [`io::ErrorKind::InvalidInput`] for non-Unicode values, malformed or unsupported
29    /// proxy endpoints, or malformed bypass entries. The error names the variable the value came
30    /// from, and identifies the offending entry for a bypass list.
31    pub fn from_env() -> io::Result<Vec<Self>> {
32        Self::from_env_with(|name| {
33            std::env::var_os(name)
34                .map(|value| {
35                    value
36                        .into_string()
37                        .map_err(|_| env_error(name, "value is not Unicode"))
38                })
39                .transpose()
40        })
41    }
42
43    pub(super) fn from_env_with(
44        mut get: impl FnMut(&str) -> io::Result<Option<String>>,
45    ) -> io::Result<Vec<Self>> {
46        fn pair(
47            get: &mut impl FnMut(&str) -> io::Result<Option<String>>,
48            lower: &'static str,
49            upper: &'static str,
50        ) -> io::Result<(&'static str, Option<String>)> {
51            match get(lower)? {
52                Some(value) => Ok((lower, Some(value))),
53                None => Ok((upper, get(upper)?)),
54            }
55        }
56        fn proxy(name: &str, value: Option<String>) -> io::Result<Option<Proxy>> {
57            value
58                .filter(|v| !v.trim().is_empty())
59                .map(|v| Proxy::new(v.trim()).map_err(|error| env_error(name, error)))
60                .transpose()
61        }
62        let (bypass_name, bypass) = pair(&mut get, "no_proxy", "NO_PROXY")?;
63        let bypass = bypass.unwrap_or_default();
64        // `*` turns proxying off, overriding inherited proxy variables without unsetting them, so
65        // the values it overrides are never parsed.
66        if bypass.split(',').any(|entry| entry.trim() == "*") {
67            return Ok(Vec::new());
68        }
69        let exceptions =
70            NoProxy::new(&bypass).map_err(|problem| env_error(bypass_name, problem))?;
71
72        let (http_name, http_value) = if get("REQUEST_METHOD")?.is_some() {
73            ("http_proxy", get("http_proxy")?)
74        } else {
75            pair(&mut get, "http_proxy", "HTTP_PROXY")?
76        };
77        let http = proxy(http_name, http_value)?;
78        let (https_name, https_value) = pair(&mut get, "https_proxy", "HTTPS_PROXY")?;
79        let https = proxy(https_name, https_value)?;
80
81        // Only a scheme without its own proxy consults the fallback, so a value that will never
82        // be used is never parsed.
83        let all = if http.is_none() || https.is_none() {
84            let (all_name, all_value) = pair(&mut get, "all_proxy", "ALL_PROXY")?;
85            proxy(all_name, all_value)?
86        } else {
87            None
88        };
89
90        let proxies = match (http, https) {
91            (None, None) => all.into_iter().collect(),
92            (http, https) => [
93                http.or_else(|| all.clone())
94                    .map(|proxy| proxy.with_schemes(ProxySchemes::Http)),
95                https
96                    .or(all)
97                    .map(|proxy| proxy.with_schemes(ProxySchemes::Https)),
98            ]
99            .into_iter()
100            .flatten()
101            .collect::<Vec<_>>(),
102        };
103        Ok(proxies
104            .into_iter()
105            .map(|proxy| proxy.with_exceptions(&exceptions))
106            .collect())
107    }
108}
109
110fn env_error(variable: &str, problem: impl fmt::Display) -> io::Error {
111    invalid(&format!("{variable}: {problem}"))
112}