1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
extern crate url;
use std::collections::HashMap;
use url::Url;
#[cfg(windows)]
mod windows;
#[cfg(target_os="macos")]
pub mod macos;
#[cfg(target_os="macos")]
extern crate plist;
#[cfg(feature = "env")]
mod env;
#[cfg(feature = "sysconfig_proxy")]
mod sysconfig_proxy;
mod errors;
mod util;
pub use errors::ProxyConfigError;
use errors::*;
use errors::ProxyConfigError::*;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProxyConfig {
pub proxies: HashMap<String, Url>,
pub whitelist: Vec<String>,
__other_stuff: (),
}
type ProxyFn = fn() -> Result<ProxyConfig>;
const METHODS: &[&ProxyFn] = &[
#[cfg(feature = "env")]
&(env::get_proxy_config as ProxyFn),
#[cfg(feature = "sysconfig_proxy")]
&(sysconfig_proxy::get_proxy_config as ProxyFn),
#[cfg(windows)]
&(windows::get_proxy_config as ProxyFn),
#[cfg(target_os="macos")]
&(macos::get_proxy_config as ProxyFn),
];
pub fn get_proxy_config() -> Result<ProxyConfig> {
let mut last_err = PlatformNotSupportedError;
for get_proxy_config in METHODS {
match get_proxy_config() {
Ok(config) => return Ok(config),
Err(e) => last_err = e,
}
}
Err(last_err)
}
pub fn get_proxy_for_url(url: Url) -> Result<Url> {
use std::ascii::AsciiExt;
match get_proxy_config() {
Ok(config) => {
for domain in config.whitelist {
if url.domain().unwrap().eq_ignore_ascii_case(&domain) {
return Err(NoProxyNeededError);
}
}
if let Some(url) = config.proxies.get(url.scheme()) {
Ok(url.clone())
} else {
Err(NoProxyForSchemeError(url.scheme().to_string()))
}
},
Err(e) => Err(e),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn smoke_test_get_proxies() {
let _ = get_proxy_config();
}
#[test]
fn smoke_test_get_proxy_for_url() {
let _ = get_proxy_for_url(Url::parse("https://google.com").unwrap());
}
}