-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
connect.rs
447 lines (395 loc) · 12.9 KB
/
connect.rs
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
//! The `Connect` trait, and supporting types.
//!
//! This module contains:
//!
//! - A default [`HttpConnector`](HttpConnector) that does DNS resolution and
//! establishes connections over TCP.
//! - The [`Connect`](Connect) trait and related types to build custom connectors.
use std::error::Error as StdError;
use std::fmt;
use std::io;
use std::net::SocketAddr;
use std::time::Duration;
use futures::{Future, Never, Poll, Async};
use futures::executor::{Executor, SpawnError, ThreadPoolBuilder};
use futures::task;
use futures::io::{AsyncRead, AsyncWrite};
use http::Uri;
use http::uri::Scheme;
use net2::TcpBuilder;
use tokio::reactor::Handle;
use tokio::net::{TcpStream, ConnectFuture};
use executor::CloneBoxedExecutor;
use super::dns;
/// Connect to a destination, returning an IO transport.
///
/// A connector receives a [`Destination`](Destination) describing how a
/// connection should be estabilished, and returns a `Future` of the
/// ready connection.
pub trait Connect: Send + Sync {
/// The connected IO Stream.
type Transport: AsyncRead + AsyncWrite + Send + 'static;
/// An error occured when trying to connect.
type Error: Into<Box<StdError + Send + Sync>>;
/// A Future that will resolve to the connected Transport.
type Future: Future<Item=(Self::Transport, Connected), Error=Self::Error> + Send;
/// Connect to a destination.
fn connect(&self, dst: Destination) -> Self::Future;
}
/// A set of properties to describe where and how to try to connect.
#[derive(Debug)]
pub struct Destination {
//pub(super) alpn: Alpn,
pub(super) uri: Uri,
}
/// Extra information about the connected transport.
///
/// This can be used to inform recipients about things like if ALPN
/// was used, or if connected to an HTTP proxy.
#[derive(Debug)]
pub struct Connected {
//alpn: Alpn,
pub(super) is_proxied: bool,
}
/*TODO: when HTTP1 Upgrades to H2 are added, this will be needed
#[derive(Debug)]
pub(super) enum Alpn {
Http1,
//H2,
//Http1OrH2
}
*/
impl Destination {
/// Get the protocol scheme.
#[inline]
pub fn scheme(&self) -> &str {
self.uri
.scheme_part()
.expect("destination uri has scheme")
.as_str()
}
/// Get the hostname.
#[inline]
pub fn host(&self) -> &str {
self.uri
.host()
.expect("destination uri has host")
}
/// Get the port, if specified.
#[inline]
pub fn port(&self) -> Option<u16> {
self.uri.port()
}
/*
/// Returns whether this connection must negotiate HTTP/2 via ALPN.
pub fn must_h2(&self) -> bool {
match self.alpn {
Alpn::Http1 => false,
Alpn::H2 => true,
}
}
*/
}
impl Connected {
/// Create new `Connected` type with empty metadata.
pub fn new() -> Connected {
Connected {
//alpn: Alpn::Http1,
is_proxied: false,
}
}
/// Set whether the connected transport is to an HTTP proxy.
///
/// This setting will affect if HTTP/1 requests written on the transport
/// will have the request-target in absolute-form or origin-form (such as
/// `GET http://hyper.rs/guide HTTP/1.1` or `GET /guide HTTP/1.1`).
///
/// Default is `false`.
pub fn proxy(mut self, is_proxied: bool) -> Connected {
self.is_proxied = is_proxied;
self
}
/*
/// Set that the connected transport negotiated HTTP/2 as it's
/// next protocol.
pub fn h2(mut self) -> Connected {
self.alpn = Alpn::H2;
self
}
*/
}
fn connect(addr: &SocketAddr, handle: &Handle) -> io::Result<ConnectFuture> {
let builder = match addr {
&SocketAddr::V4(_) => TcpBuilder::new_v4()?,
&SocketAddr::V6(_) => TcpBuilder::new_v6()?,
};
if cfg!(windows) {
// Windows requires a socket be bound before calling connect
let any: SocketAddr = match addr {
&SocketAddr::V4(_) => {
([0, 0, 0, 0], 0).into()
},
&SocketAddr::V6(_) => {
([0, 0, 0, 0, 0, 0, 0, 0], 0).into()
}
};
builder.bind(any)?;
}
Ok(TcpStream::connect_std(builder.to_tcp_stream()?, addr, handle))
}
/// A connector for the `http` scheme.
///
/// Performs DNS resolution in a thread pool, and then connects over TCP.
#[derive(Clone)]
pub struct HttpConnector {
executor: HttpConnectExecutor,
enforce_http: bool,
handle: Handle,
keep_alive_timeout: Option<Duration>,
}
impl HttpConnector {
/// Construct a new HttpConnector.
///
/// Takes number of DNS worker threads.
#[inline]
pub fn new(threads: usize, handle: &Handle) -> HttpConnector {
let pool = ThreadPoolBuilder::new()
.name_prefix("hyper-dns")
.pool_size(threads)
.create();
HttpConnector::new_with_executor(pool, handle)
}
/// Construct a new HttpConnector.
///
/// Takes an executor to run blocking tasks on.
#[inline]
pub fn new_with_executor<E: 'static>(executor: E, handle: &Handle) -> HttpConnector
where E: Executor + Clone + Send + Sync
{
HttpConnector {
executor: HttpConnectExecutor(Box::new(executor)),
enforce_http: true,
handle: handle.clone(),
keep_alive_timeout: None,
}
}
/// Option to enforce all `Uri`s have the `http` scheme.
///
/// Enabled by default.
#[inline]
pub fn enforce_http(&mut self, is_enforced: bool) {
self.enforce_http = is_enforced;
}
/// Set that all sockets have `SO_KEEPALIVE` set with the supplied duration.
///
/// If `None`, the option will not be set.
///
/// Default is `None`.
#[inline]
pub fn set_keepalive(&mut self, dur: Option<Duration>) {
self.keep_alive_timeout = dur;
}
}
impl fmt::Debug for HttpConnector {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("HttpConnector")
.finish()
}
}
impl Connect for HttpConnector {
type Transport = TcpStream;
type Error = io::Error;
type Future = HttpConnecting;
fn connect(&self, dst: Destination) -> Self::Future {
trace!("Http::connect({:?})", dst.uri);
if self.enforce_http {
if dst.uri.scheme_part() != Some(&Scheme::HTTP) {
return invalid_url(InvalidUrl::NotHttp, &self.handle);
}
} else if dst.uri.scheme_part().is_none() {
return invalid_url(InvalidUrl::MissingScheme, &self.handle);
}
let host = match dst.uri.host() {
Some(s) => s,
None => return invalid_url(InvalidUrl::MissingAuthority, &self.handle),
};
let port = match dst.uri.port() {
Some(port) => port,
None => if dst.uri.scheme_part() == Some(&Scheme::HTTPS) { 443 } else { 80 },
};
HttpConnecting {
state: State::Lazy(self.executor.clone(), host.into(), port),
handle: self.handle.clone(),
keep_alive_timeout: self.keep_alive_timeout,
}
}
}
#[inline]
fn invalid_url(err: InvalidUrl, handle: &Handle) -> HttpConnecting {
HttpConnecting {
state: State::Error(Some(io::Error::new(io::ErrorKind::InvalidInput, err))),
handle: handle.clone(),
keep_alive_timeout: None,
}
}
#[derive(Debug, Clone, Copy)]
enum InvalidUrl {
MissingScheme,
NotHttp,
MissingAuthority,
}
impl fmt::Display for InvalidUrl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
impl StdError for InvalidUrl {
fn description(&self) -> &str {
match *self {
InvalidUrl::MissingScheme => "invalid URL, missing scheme",
InvalidUrl::NotHttp => "invalid URL, scheme must be http",
InvalidUrl::MissingAuthority => "invalid URL, missing domain",
}
}
}
/// A Future representing work to connect to a URL.
#[must_use = "futures do nothing unless polled"]
pub struct HttpConnecting {
state: State,
handle: Handle,
keep_alive_timeout: Option<Duration>,
}
enum State {
Lazy(HttpConnectExecutor, String, u16),
Resolving(dns::Resolving),
Connecting(ConnectingTcp),
Error(Option<io::Error>),
}
impl Future for HttpConnecting {
type Item = (TcpStream, Connected);
type Error = io::Error;
fn poll(&mut self, cx: &mut task::Context) -> Poll<Self::Item, Self::Error> {
loop {
let state;
match self.state {
State::Lazy(ref mut executor, ref mut host, port) => {
// If the host is already an IP addr (v4 or v6),
// skip resolving the dns and start connecting right away.
if let Some(addrs) = dns::IpAddrs::try_parse(host, port) {
state = State::Connecting(ConnectingTcp {
addrs: addrs,
current: None
})
} else {
let host = ::std::mem::replace(host, String::new());
state = State::Resolving(dns::Resolving::spawn(host, port, executor));
}
},
State::Resolving(ref mut future) => {
let addrs = try_ready!(future.poll(cx));
state = State::Connecting(ConnectingTcp {
addrs: addrs,
current: None,
});
},
State::Connecting(ref mut c) => {
let sock = try_ready!(c.poll(cx, &self.handle));
if let Some(dur) = self.keep_alive_timeout {
sock.set_keepalive(Some(dur))?;
}
return Ok(Async::Ready((sock, Connected::new())));
},
State::Error(ref mut e) => return Err(e.take().expect("polled more than once")),
}
self.state = state;
}
}
}
impl fmt::Debug for HttpConnecting {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("HttpConnecting")
}
}
struct ConnectingTcp {
addrs: dns::IpAddrs,
current: Option<ConnectFuture>,
}
impl ConnectingTcp {
// not a Future, since passing a &Handle to poll
fn poll(&mut self, cx: &mut task::Context, handle: &Handle) -> Poll<TcpStream, io::Error> {
let mut err = None;
loop {
if let Some(ref mut current) = self.current {
match current.poll(cx) {
Ok(ok) => return Ok(ok),
Err(e) => {
trace!("connect error {:?}", e);
err = Some(e);
if let Some(addr) = self.addrs.next() {
debug!("connecting to {}", addr);
*current = connect(&addr, handle)?;
continue;
}
}
}
} else if let Some(addr) = self.addrs.next() {
debug!("connecting to {}", addr);
self.current = Some(connect(&addr, handle)?);
continue;
}
return Err(err.take().expect("missing connect error"));
}
}
}
#[derive(Clone)]
struct HttpConnectExecutor(Box<CloneBoxedExecutor>);
impl Executor for HttpConnectExecutor {
fn spawn(
&mut self,
f: Box<Future<Item = (), Error = Never> + 'static + Send>
) -> Result<(), SpawnError> {
self.0.spawn(f)
}
fn status(&self) -> Result<(), SpawnError> {
self.0.status()
}
}
#[cfg(test)]
mod tests {
#![allow(deprecated)]
use std::io;
use futures::executor::block_on;
use tokio::runtime::Runtime;
use super::{Connect, Destination, HttpConnector};
#[test]
fn test_errors_missing_authority() {
let runtime = Runtime::new().unwrap();
let uri = "/foo/bar?baz".parse().unwrap();
let dst = Destination {
uri,
};
let connector = HttpConnector::new(1, runtime.handle());
assert_eq!(block_on(connector.connect(dst)).unwrap_err().kind(), io::ErrorKind::InvalidInput);
}
#[test]
fn test_errors_enforce_http() {
let runtime = Runtime::new().unwrap();
let uri = "https://example.domain/foo/bar?baz".parse().unwrap();
let dst = Destination {
uri,
};
let connector = HttpConnector::new(1, runtime.handle());
assert_eq!(block_on(connector.connect(dst)).unwrap_err().kind(), io::ErrorKind::InvalidInput);
}
#[test]
fn test_errors_missing_scheme() {
let runtime = Runtime::new().unwrap();
let uri = "example.domain".parse().unwrap();
let dst = Destination {
uri,
};
let connector = HttpConnector::new(1, runtime.handle());
assert_eq!(block_on(connector.connect(dst)).unwrap_err().kind(), io::ErrorKind::InvalidInput);
}
}