cargo/util/network/
proxy.rs

1//! Utilities for network proxies.
2
3use crate::util::context::CargoHttpConfig;
4use crate::util::context::GlobalContext;
5
6/// Proxy environment variables that are picked up by libcurl.
7const LIBCURL_HTTP_PROXY_ENVS: [&str; 4] =
8    ["http_proxy", "HTTP_PROXY", "https_proxy", "HTTPS_PROXY"];
9
10/// Finds an explicit HTTP proxy if one is available.
11///
12/// Favor [Cargo's `http.proxy`], then [Git's `http.proxy`].
13/// Proxies specified via environment variables are picked up by libcurl.
14/// See [`LIBCURL_HTTP_PROXY_ENVS`].
15///
16/// [Cargo's `http.proxy`]: https://doc.rust-lang.org/nightly/cargo/reference/config.html#httpproxy
17/// [Git's `http.proxy`]: https://git-scm.com/docs/git-config#Documentation/git-config.txt-httpproxy
18pub fn http_proxy(http: &CargoHttpConfig) -> Option<String> {
19    if let Some(s) = &http.proxy {
20        return Some(s.into());
21    }
22    git2::Config::open_default()
23        .and_then(|cfg| cfg.get_string("http.proxy"))
24        .ok()
25}
26
27/// Determine if an http proxy exists.
28///
29/// Checks the following for existence, in order:
30///
31/// * Cargo's `http.proxy`
32/// * Git's `http.proxy`
33/// * `http_proxy` env var
34/// * `HTTP_PROXY` env var
35/// * `https_proxy` env var
36/// * `HTTPS_PROXY` env var
37pub fn http_proxy_exists(http: &CargoHttpConfig, gctx: &GlobalContext) -> bool {
38    http_proxy(http).is_some()
39        || LIBCURL_HTTP_PROXY_ENVS
40            .iter()
41            .any(|v| gctx.get_env(v).is_ok())
42}