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
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use std::collections::{HashMap, HashSet};

use url::Url;

#[cfg(windows)]
mod windows;

#[cfg(target_os="macos")]
mod macos;

#[cfg(feature = "env")]
mod env;

#[cfg(feature = "sysconfig_proxy")]
mod sysconfig_proxy;

mod errors;

use errors::Error;

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProxyConfig {
    pub proxies: HashMap<String, String>,
    pub whitelist: HashSet<String>,
    pub exclude_simple: bool,
    __other_stuff: (),
}

impl ProxyConfig {
    pub fn get_proxy_for_url(&self, url: Url) -> Option<String> {
        let host = match url.host_str() {
            Some(host) => host.to_lowercase(),
            None => return None,
        };

        if self.exclude_simple && !host.chars().any(|c| c == '.') {
            return None
        }

        if self.whitelist.contains(&host) {
            return None
        }

        // TODO: Wildcard matches on IP address, e.g. 192.168.*.*
        // TODO: Subnet matches on IP address, e.g. 192.168.16.0/24

        if self.whitelist.iter().any(|s| {
            if let Some(pos) = s.rfind('*') {
                let slice = &s[pos + 1..];
                return slice.len() > 0 && host.ends_with(slice)
            }
            false 
        }) { return None }

        self.proxies.get(url.scheme()).map(|s| s.to_string().to_lowercase())
    }
}

type ProxyFn = fn() -> Result<Option<ProxyConfig>>;

const METHODS: &[&ProxyFn] = &[
    #[cfg(feature = "env")]
    &(env::get_proxy_config as ProxyFn),
    #[cfg(feature = "sysconfig_proxy")]
    &(sysconfig_proxy::get_proxy_config as ProxyFn), //This configurator has to come after the `env` configurator, because environment variables take precedence over /etc/sysconfig/proxy
    #[cfg(windows)]
    &(windows::get_proxy_config as ProxyFn),
    #[cfg(target_os="macos")]
    &(macos::get_proxy_config as ProxyFn),
];

pub fn get_proxy_config() -> Result<Option<ProxyConfig>> {
    if METHODS.len() == 0 {
        return Err(Error::PlatformNotSupported)
    }

    let mut last_err: Option<Error> = None;
    for get_proxy_config in METHODS {
        match get_proxy_config() {
            Ok(Some(config)) => return Ok(Some(config)),
            Err(e) => last_err = Some(e),
            _ => {},
        }
    }

    if let Some(e) = last_err {
        return Err(e)
    }

    Ok(None)
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! map(
        { $($key:expr => $value:expr),+ } => {
            {
                let mut m = ::std::collections::HashMap::new();
                $(
                    m.insert($key, $value);
                )+
                m
            }
         };
    );

    #[test]
    fn smoke_test_get_proxies() {
        let _ = get_proxy_config();
    }

    #[test]
    fn smoke_test_get_proxy_for_url() {
        if let Some(proxy_config) = get_proxy_config().unwrap() {
            let _ = proxy_config.get_proxy_for_url(Url::parse("https://google.com").unwrap());
        }
    }

    #[test]
    fn test_get_proxy_for_url() {
        let proxy_config = ProxyConfig { 
            proxies: map!{ 
                "http".into() => "1.1.1.1".into(), 
                "https".into() => "2.2.2.2".into() 
            },
            whitelist: vec![
                "www.devolutions.net", 
                "*.microsoft.com", 
                "*apple.com"
            ].into_iter().map(|s| s.to_string()).collect(),
            exclude_simple: true,
            ..Default::default() 
        };

        assert_eq!(proxy_config.get_proxy_for_url(Url::parse("http://simpledomain").unwrap()), None);
        assert_eq!(proxy_config.get_proxy_for_url(Url::parse("http://simple.domain").unwrap()), Some("1.1.1.1".into()));
        assert_eq!(proxy_config.get_proxy_for_url(Url::parse("http://www.devolutions.net").unwrap()), None);
        assert_eq!(proxy_config.get_proxy_for_url(Url::parse("http://www.microsoft.com").unwrap()), None);
        assert_eq!(proxy_config.get_proxy_for_url(Url::parse("http://www.microsoft.com.fun").unwrap()), Some("1.1.1.1".into()));
        assert_eq!(proxy_config.get_proxy_for_url(Url::parse("http://test.apple.com").unwrap()), None);
        assert_eq!(proxy_config.get_proxy_for_url(Url::parse("https://test.apple.net").unwrap()), Some("2.2.2.2".into()));
    }
}