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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//! This crate provides a chroot/sandbox friendly https client.
//!
//! It doesn't depend on any files from the filesystem which would usually
//! cause issues if /etc/resolv.conf or ca-certificates can not be found.
//!
//! # Example
//!
//! ```
//! extern crate chrootable_https;
//! use chrootable_https::{Resolver, Client};
//!
//! let resolver = Resolver::cloudflare();
//! let client = Client::new(resolver);
//!
//! let reply = client.get("https://httpbin.org/anything").wait_for_response().expect("request failed");
//! println!("{:#?}", reply);
//! ```

#![warn(unused_extern_crates)]
pub use http;
pub use hyper;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate log;

use bytes::Bytes;
pub use http::header;
use http::response::Parts;
pub use http::Request;
use hyper::client::connect::HttpConnector;
use hyper::rt::Future;
pub use hyper::Body;
use hyper_rustls::HttpsConnector;

use futures::{future, Poll, Stream};
use tokio::prelude::FutureExt;
use tokio::runtime::Runtime;

pub use http::Uri;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::time::Duration;

pub mod cache;
mod connector;
pub mod dns;
pub mod socks5;
use self::connector::Connector;
pub use crate::dns::{DnsResolver, RecordType, Resolver};

pub mod errors {
    pub use failure::{Error, ResultExt};
    pub type Result<T> = ::std::result::Result<T, Error>;
}
pub use crate::errors::*;

/// A Client to make outgoing HTTP requests.
///
/// Uses an specific DNS resolver.
#[derive(Debug)]
pub struct Client<R: DnsResolver> {
    client: hyper::Client<HttpsConnector<Connector<HttpConnector, R>>>,
}

impl<R: DnsResolver + 'static> Client<R> {
    /// Create a new client with a specific DNS resolver.
    ///
    /// This bypasses `/etc/resolv.conf`.
    pub fn new(resolver: R) -> Client<R> {
        let https = Connector::new(resolver)
            .with_https();
        let client = hyper::Client::builder()
            .keep_alive(false)
            .build::<_, hyper::Body>(https);

        Client {
            client,
        }
    }

    /// Shorthand function to do a GET request with [`HttpClient::request`].
    ///
    /// [`HttpClient::request`]: trait.HttpClient.html#tymethod.request
    pub fn get(&self, url: &str) -> ResponseFuture {
        let url = match url.parse::<Uri>() {
            Ok(url) => url,
            Err(e) => return ResponseFuture::new(future::err(e.into())),
        };

        let mut request = Request::builder();
        let request = match request.uri(url).body(Body::empty()) {
            Ok(request) => request,
            Err(e) => return ResponseFuture::new(future::err(e.into())),
        };

        self.request(request)
    }
}

impl Client<Resolver> {
    /// Create a new client with the system resolver from `/etc/resolv.conf`.
    pub fn with_system_resolver() -> Result<Client<Resolver>> {
        let resolver = Resolver::from_system()?;
        Ok(Client::new(resolver))
    }

    /// Create a new client that is locked to a socks5 proxy
    pub fn with_socks5(proxy: SocketAddr) -> Client<Resolver> {
        let resolver = Resolver::empty();
        let https = Connector::new(resolver)
            .with_socks5(proxy)
            .with_https();
        let client = hyper::Client::builder()
            .keep_alive(false)
            .build::<_, hyper::Body>(https);

        Client {
            client,
        }
    }
}

/// Generic abstraction over HTTP clients.
pub trait HttpClient {
    fn request(&self, request: Request<hyper::Body>) -> ResponseFuture;
}

impl<R: DnsResolver + 'static> HttpClient for Client<R> {
    fn request(&self, request: Request<hyper::Body>) -> ResponseFuture {
        let client = self.client.clone();

        info!("sending request to {:?}", request.uri());
        let fut = client.request(request).map_err(Error::from)
            .and_then(|res| {
                debug!("http response: {:?}", res);
                let (parts, body) = res.into_parts();
                let body = body.concat2().map_err(Error::from);
                (future::ok(parts), body)
            }).map_err(Error::from);

        let reply = fut.and_then(|(parts, body)| {
            let body = body.into_bytes();
            let reply = Response::from((parts, body));
            info!("got reply {:?}", reply);
            Ok(reply)
        });

        ResponseFuture::new(reply)
    }
}

/// A `Future` that will resolve to an HTTP Response.
#[must_use = "futures do nothing unless polled"]
pub struct ResponseFuture(Box<Future<Item = Response, Error = Error> + Send>);

impl ResponseFuture {
    /// Creates a new `ResponseFuture`.
    pub(crate) fn new<F>(inner: F) -> Self
    where
        F: Future<Item = Response, Error = Error> + Send + 'static,
    {
        ResponseFuture(Box::new(inner))
    }

    /// Set a timeout (default setting is no timeout).
    pub fn with_timeout(self, timeout: Option<Duration>) -> Self {
        match timeout {
            Some(timeout) => {
                let fut = self.timeout(timeout)
                    .map_err(|err| match err.into_inner() {
                        Some(err) => err,
                        _ => format_err!("Request timed out"),
                    });
                ResponseFuture(Box::new(fut))
            },
            _ => self,
        }
    }

    /// Drives this future to completion, eventually returning an HTTP response.
    pub fn wait_for_response(self) -> Result<Response> {
        let mut rt = Runtime::new()?;
        rt.block_on(self)
    }
}

impl Future for ResponseFuture {
    type Item = Response;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.0.poll()
    }
}

/// Represents an HTTP response.
#[derive(Debug)]
pub struct Response {
    pub status: u16,
    pub headers: HashMap<String, String>,
    pub cookies: Vec<String>,
    pub body: Bytes,
}

impl From<(Parts, Bytes)> for Response {
    fn from(x: (Parts, Bytes)) -> Response {
        let parts = x.0;
        let body = x.1;

        let cookies = parts
            .headers
            .get_all("set-cookie")
            .into_iter()
            .flat_map(|x| x.to_str().map(|x| x.to_owned()).ok())
            .collect();

        let mut headers = HashMap::new();

        for (k, v) in parts.headers {
            if let Some(k) = k {
                if let Ok(v) = v.to_str() {
                    let k = String::from(k.as_str());
                    let v = String::from(v);

                    headers.insert(k, v);
                }
            }
        }

        Response {
            status: parts.status.as_u16(),
            headers,
            cookies,
            body,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dns::Resolver;
    use std::time::{Duration, Instant};

    #[test]
    fn verify_200_http() {
        let resolver = Resolver::cloudflare();

        let client = Client::new(resolver);
        let reply = client
            .get("http://httpbin.org/anything")
            .wait_for_response()
            .expect("request failed");
        assert_eq!(reply.status, 200);
    }

    #[test]
    fn verify_200_https() {
        let resolver = Resolver::cloudflare();

        let client = Client::new(resolver);
        let reply = client
            .get("https://httpbin.org/anything")
            .wait_for_response()
            .expect("request failed");
        assert_eq!(reply.status, 200);
    }

    #[test]
    fn verify_200_https_ipaddr() {
        let resolver = Resolver::cloudflare();

        let client = Client::new(resolver);
        let reply = client
            .get("http://1.1.1.1/")
            .wait_for_response()
            .expect("request failed");
        assert_eq!(reply.status, 301);
    }

    #[test]
    fn verify_200_https_system_resolver() {
        let client = Client::with_system_resolver().expect("failed to create client");
        let reply = client
            .get("https://httpbin.org/anything")
            .wait_for_response()
            .expect("request failed");
        assert_eq!(reply.status, 200);
    }

    #[test]
    fn verify_302() {
        let resolver = Resolver::cloudflare();

        let client = Client::new(resolver);
        let reply = client
            .get("https://httpbin.org/redirect-to?url=/anything&status=302")
            .wait_for_response()
            .expect("request failed");
        assert_eq!(reply.status, 302);
    }

    #[test]
    fn verify_timeout() {
        let resolver = Resolver::cloudflare();
        let client = Client::new(resolver);

        let start = Instant::now();
        let _reply = client.get("http://1.2.3.4")
            .with_timeout(Some(Duration::from_millis(250)))
            .wait_for_response().err();
        let end = Instant::now();

        assert!(end.duration_since(start) < Duration::from_secs(1));
    }
}