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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use std::fmt;
use std::sync::Arc;

use hyper::Uri;
use {into_url, IntoUrl, Url};

/// Configuration of a proxy that a `Client` should pass requests to.
///
/// A `Proxy` has a couple pieces to it:
///
/// - a URL of how to talk to the proxy
/// - rules on what `Client` requests should be directed to the proxy
///
/// For instance, let's look at `Proxy::http`:
///
/// ```
/// # extern crate reqwest;
/// # fn run() -> Result<(), Box<::std::error::Error>> {
/// let proxy = reqwest::Proxy::http("https://secure.example")?;
/// # Ok(())
/// # }
/// # fn main() {}
/// ```
///
/// This proxy will intercept all HTTP requests, and make use of the proxy
/// at `https://secure.example`. A request to `http://hyper.rs` will talk
/// to your proxy. A request to `https://hyper.rs` will not.
///
/// Multiple `Proxy` rules can be configured for a `Client`. The `Client` will
/// check each `Proxy` in the order it was added. This could mean that a
/// `Proxy` added first with eager intercept rules, such as `Proxy::all`,
/// would prevent a `Proxy` later in the list from ever working, so take care.
#[derive(Clone, Debug)]
pub struct Proxy {
    intercept: Intercept,
}

impl Proxy {
    /// Proxy all HTTP traffic to the passed URL.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate reqwest;
    /// # fn run() -> Result<(), Box<::std::error::Error>> {
    /// let client = reqwest::Client::builder()
    ///     .proxy(reqwest::Proxy::http("https://my.prox")?)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// # fn main() {}
    /// ```
    pub fn http<U: IntoUrl>(url: U) -> ::Result<Proxy> {
        let uri = ::into_url::to_uri(&try_!(url.into_url()));
        Ok(Proxy::new(Intercept::Http(uri)))
    }

    /// Proxy all HTTPS traffic to the passed URL.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate reqwest;
    /// # fn run() -> Result<(), Box<::std::error::Error>> {
    /// let client = reqwest::Client::builder()
    ///     .proxy(reqwest::Proxy::https("https://example.prox:4545")?)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// # fn main() {}
    /// ```
    pub fn https<U: IntoUrl>(url: U) -> ::Result<Proxy> {
        let uri = ::into_url::to_uri(&try_!(url.into_url()));
        Ok(Proxy::new(Intercept::Https(uri)))
    }

    /// Proxy **all** traffic to the passed URL.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate reqwest;
    /// # fn run() -> Result<(), Box<::std::error::Error>> {
    /// let client = reqwest::Client::builder()
    ///     .proxy(reqwest::Proxy::all("http://pro.xy")?)
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// # fn main() {}
    /// ```
    pub fn all<U: IntoUrl>(url: U) -> ::Result<Proxy> {
        let uri = ::into_url::to_uri(&try_!(url.into_url()));
        Ok(Proxy::new(Intercept::All(uri)))
    }

    /// Provide a custom function to determine what traffix to proxy to where.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate reqwest;
    /// # fn run() -> Result<(), Box<::std::error::Error>> {
    /// let target = reqwest::Url::parse("https://my.prox")?;
    /// let client = reqwest::Client::builder()
    ///     .proxy(reqwest::Proxy::custom(move |url| {
    ///         if url.host_str() == Some("hyper.rs") {
    ///             Some(target.clone())
    ///         } else {
    ///             None
    ///         }
    ///     }))
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// # fn main() {}
    pub fn custom<F>(fun: F) -> Proxy
    where F: Fn(&Url) -> Option<Url> + Send + Sync + 'static {
        Proxy::new(Intercept::Custom(Custom(Arc::new(fun))))
    }

    /*
    pub fn unix<P: AsRef<Path>(path: P) -> Proxy {

    }
    */

    fn new(intercept: Intercept) -> Proxy {
        Proxy {
            intercept: intercept,
        }
    }

    fn proxies(&self, url: &Url) -> bool {
        match self.intercept {
            Intercept::All(..) => true,
            Intercept::Http(..) => url.scheme() == "http",
            Intercept::Https(..) => url.scheme() == "https",
            Intercept::Custom(ref fun) => (fun.0)(url).is_some(),
        }
    }


    fn intercept(&self, uri: &Uri) -> Option<Uri> {
        match self.intercept {
            Intercept::All(ref u) => Some(u.clone()),
            Intercept::Http(ref u) => {
                if uri.scheme() == Some("http") {
                    Some(u.clone())
                } else {
                    None
                }
            },
            Intercept::Https(ref u) => {
                if uri.scheme() == Some("https") {
                    Some(u.clone())
                } else {
                    None
                }
            },
            Intercept::Custom(ref fun) => {
                (fun.0)(&into_url::to_url(uri))
                    .map(|u| into_url::to_uri(&u))
            },
        }
    }
}

#[derive(Clone, Debug)]
enum Intercept {
    All(Uri),
    Http(Uri),
    Https(Uri),
    Custom(Custom),
}

#[derive(Clone)]
struct Custom(Arc<Fn(&Url) -> Option<Url> + Send + Sync + 'static>);

impl fmt::Debug for Custom {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("_")
    }
}

// pub(crate)

pub fn intercept(proxy: &Proxy, uri: &Uri) -> Option<Uri> {
    proxy.intercept(uri)
}

pub fn is_proxied(proxies: &[Proxy], uri: &Url) -> bool {
    proxies.iter().any(|p| p.proxies(uri))
}

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

    fn uri(s: &str) -> Uri {
        s.parse().unwrap()
    }

    fn url(s: &str) -> Url {
        s.parse().unwrap()
    }

    #[test]
    fn test_http() {
        let target = "http://example.domain/";
        let p = Proxy::http(target).unwrap();

        let http = "http://hyper.rs";
        let other = "https://hyper.rs";

        assert!(p.proxies(&url(http)));
        assert_eq!(p.intercept(&uri(http)).unwrap(), target);
        assert!(!p.proxies(&url(other)));
        assert!(p.intercept(&uri(other)).is_none());
    }

    #[test]
    fn test_https() {
        let target = "http://example.domain/";
        let p = Proxy::https(target).unwrap();

        let http = "http://hyper.rs";
        let other = "https://hyper.rs";

        assert!(!p.proxies(&url(http)));
        assert!(p.intercept(&uri(http)).is_none());
        assert!(p.proxies(&url(other)));
        assert_eq!(p.intercept(&uri(other)).unwrap(), target);
    }

    #[test]
    fn test_all() {
        let target = "http://example.domain/";
        let p = Proxy::all(target).unwrap();

        let http = "http://hyper.rs";
        let https = "https://hyper.rs";
        let other = "x-youve-never-heard-of-me-mr-proxy://hyper.rs";

        assert!(p.proxies(&url(http)));
        assert!(p.proxies(&url(https)));
        assert!(p.proxies(&url(other)));

        assert_eq!(p.intercept(&uri(http)).unwrap(), target);
        assert_eq!(p.intercept(&uri(https)).unwrap(), target);
        assert_eq!(p.intercept(&uri(other)).unwrap(), target);
    }


    #[test]
    fn test_custom() {
        let target1 = "http://example.domain/";
        let target2 = "https://example.domain/";
        let p = Proxy::custom(move |url| {
            if url.host_str() == Some("hyper.rs") {
                target1.parse().ok()
            } else if url.scheme() == "http" {
                target2.parse().ok()
            } else {
                None
            }
        });

        let http = "http://seanmonstar.com";
        let https = "https://hyper.rs";
        let other = "x-youve-never-heard-of-me-mr-proxy://seanmonstar.com";

        assert!(p.proxies(&url(http)));
        assert!(p.proxies(&url(https)));
        assert!(!p.proxies(&url(other)));

        assert_eq!(p.intercept(&uri(http)).unwrap(), target2);
        assert_eq!(p.intercept(&uri(https)).unwrap(), target1);
        assert!(p.intercept(&uri(other)).is_none());
    }

    #[test]
    fn test_is_proxied() {
        let proxies = vec![
            Proxy::http("http://example.domain").unwrap(),
            Proxy::https("http://other.domain").unwrap(),
        ];

        let http = "http://hyper.rs".parse().unwrap();
        let https = "https://hyper.rs".parse().unwrap();
        let other = "x-other://hyper.rs".parse().unwrap();

        assert!(is_proxied(&proxies, &http));
        assert!(is_proxied(&proxies, &https));
        assert!(!is_proxied(&proxies, &other));
    }

}