1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-01-19 22:14:40 +01:00
actix-net/src/connector.rs

269 lines
7.6 KiB
Rust
Raw Normal View History

2018-08-23 20:47:41 -07:00
use std::collections::VecDeque;
use std::io;
use std::net::SocketAddr;
2018-08-28 16:24:36 -07:00
use futures::{
future::{ok, FutureResult},
Async, Future, Poll,
};
2018-08-23 20:47:41 -07:00
use tokio;
use tokio_tcp::{ConnectFuture, TcpStream};
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
use trust_dns_resolver::lookup_ip::LookupIpFuture;
2018-08-28 16:24:36 -07:00
use trust_dns_resolver::system_conf::read_system_conf;
2018-08-23 20:47:41 -07:00
use trust_dns_resolver::{AsyncResolver, Background};
2018-08-28 16:24:36 -07:00
use super::{NewService, Service};
2018-08-23 20:47:41 -07:00
#[derive(Fail, Debug)]
pub enum ConnectorError {
/// Failed to resolve the hostname
#[fail(display = "Failed resolving hostname: {}", _0)]
Resolver(String),
/// Address is invalid
#[fail(display = "Invalid input: {}", _0)]
InvalidInput(&'static str),
/// Connection io error
#[fail(display = "{}", _0)]
IoError(io::Error),
}
2018-08-28 16:24:36 -07:00
pub struct ConnectionInfo {
pub host: String,
pub addr: SocketAddr,
}
2018-08-23 20:47:41 -07:00
pub struct Connector {
resolver: AsyncResolver,
}
2018-08-28 16:24:36 -07:00
impl Default for Connector {
fn default() -> Self {
let (cfg, opts) = if let Ok((cfg, opts)) = read_system_conf() {
(cfg, opts)
} else {
(ResolverConfig::default(), ResolverOpts::default())
2018-08-23 20:47:41 -07:00
};
2018-08-28 16:24:36 -07:00
Connector::new(cfg, opts)
}
}
impl Connector {
pub fn new(cfg: ResolverConfig, opts: ResolverOpts) -> Self {
let (resolver, bg) = AsyncResolver::new(cfg, opts);
tokio::spawn(bg);
2018-08-23 20:47:41 -07:00
Connector { resolver }
}
2018-08-27 20:32:49 -07:00
2018-08-28 16:24:36 -07:00
pub fn new_service<E>() -> impl NewService<
Request = String,
Response = (ConnectionInfo, TcpStream),
Error = ConnectorError,
InitError = E,
> + Clone {
|| -> FutureResult<Connector, E> { ok(Connector::default()) }
}
pub fn new_service_with_config<E>(
cfg: ResolverConfig, opts: ResolverOpts,
) -> impl NewService<
Request = String,
Response = (ConnectionInfo, TcpStream),
Error = ConnectorError,
InitError = E,
> + Clone {
move || -> FutureResult<Connector, E> { ok(Connector::new(cfg.clone(), opts.clone())) }
2018-08-27 20:32:49 -07:00
}
}
impl Clone for Connector {
fn clone(&self) -> Self {
Connector {
resolver: self.resolver.clone(),
}
}
2018-08-23 20:47:41 -07:00
}
impl Service for Connector {
type Request = String;
2018-08-28 16:24:36 -07:00
type Response = (ConnectionInfo, TcpStream);
2018-08-23 20:47:41 -07:00
type Error = ConnectorError;
type Future = ConnectorFuture;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, addr: String) -> Self::Future {
2018-08-28 16:24:36 -07:00
let fut = ResolveFut::new(addr, 0, &self.resolver);
2018-08-28 16:24:36 -07:00
ConnectorFuture { fut, fut2: None }
2018-08-23 20:47:41 -07:00
}
}
pub struct ConnectorFuture {
fut: ResolveFut,
fut2: Option<TcpConnector>,
}
impl Future for ConnectorFuture {
2018-08-28 16:24:36 -07:00
type Item = (ConnectionInfo, TcpStream);
2018-08-23 20:47:41 -07:00
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(ref mut fut) = self.fut2 {
2018-08-28 16:24:36 -07:00
return fut.poll();
2018-08-23 20:47:41 -07:00
}
match self.fut.poll()? {
2018-08-28 16:24:36 -07:00
Async::Ready((host, addrs)) => {
self.fut2 = Some(TcpConnector::new(host, addrs));
2018-08-23 20:47:41 -07:00
self.poll()
2018-08-23 22:12:10 -07:00
}
Async::NotReady => Ok(Async::NotReady),
2018-08-23 20:47:41 -07:00
}
}
}
/// Resolver future
struct ResolveFut {
2018-08-28 16:24:36 -07:00
host: Option<String>,
2018-08-23 20:47:41 -07:00
port: u16,
2018-08-28 16:24:36 -07:00
lookup: Option<Background<LookupIpFuture>>,
2018-08-23 20:47:41 -07:00
addrs: Option<VecDeque<SocketAddr>>,
error: Option<ConnectorError>,
error2: Option<String>,
}
impl ResolveFut {
2018-08-28 16:24:36 -07:00
pub fn new(addr: String, port: u16, resolver: &AsyncResolver) -> Self {
2018-08-23 20:47:41 -07:00
// we need to do dns resolution
match ResolveFut::parse(addr.as_ref(), port) {
Ok((host, port)) => ResolveFut {
port,
2018-08-28 16:24:36 -07:00
host: Some(host.to_owned()),
2018-08-23 20:47:41 -07:00
lookup: Some(resolver.lookup_ip(host)),
addrs: None,
error: None,
error2: None,
},
Err(err) => ResolveFut {
port,
2018-08-28 16:24:36 -07:00
host: None,
2018-08-23 20:47:41 -07:00
lookup: None,
addrs: None,
error: Some(err),
error2: None,
},
}
}
fn parse(addr: &str, port: u16) -> Result<(&str, u16), ConnectorError> {
macro_rules! try_opt {
($e:expr, $msg:expr) => {
match $e {
Some(r) => r,
None => return Err(ConnectorError::InvalidInput($msg)),
}
};
}
// split the string by ':' and convert the second part to u16
let mut parts_iter = addr.splitn(2, ':');
let host = try_opt!(parts_iter.next(), "invalid socket address");
let port_str = parts_iter.next().unwrap_or("");
let port: u16 = port_str.parse().unwrap_or(port);
Ok((host, port))
}
}
impl Future for ResolveFut {
2018-08-28 16:24:36 -07:00
type Item = (String, VecDeque<SocketAddr>);
2018-08-23 20:47:41 -07:00
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
if let Some(err) = self.error.take() {
Err(err)
} else if let Some(err) = self.error2.take() {
Err(ConnectorError::Resolver(err))
} else if let Some(addrs) = self.addrs.take() {
2018-08-28 16:24:36 -07:00
Ok(Async::Ready((self.host.take().unwrap(), addrs)))
2018-08-23 20:47:41 -07:00
} else {
match self.lookup.as_mut().unwrap().poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(ips)) => {
let addrs: VecDeque<_> = ips
.iter()
.map(|ip| SocketAddr::new(ip, self.port))
.collect();
if addrs.is_empty() {
Err(ConnectorError::Resolver(
"Expect at least one A dns record".to_owned(),
))
} else {
2018-08-28 16:24:36 -07:00
Ok(Async::Ready((self.host.take().unwrap(), addrs)))
2018-08-23 20:47:41 -07:00
}
}
Err(err) => Err(ConnectorError::Resolver(format!("{}", err))),
}
}
}
}
/// Tcp stream connector
pub struct TcpConnector {
2018-08-28 16:24:36 -07:00
host: Option<String>,
addr: Option<SocketAddr>,
2018-08-23 20:47:41 -07:00
addrs: VecDeque<SocketAddr>,
stream: Option<ConnectFuture>,
}
impl TcpConnector {
2018-08-28 16:24:36 -07:00
pub fn new(host: String, addrs: VecDeque<SocketAddr>) -> TcpConnector {
2018-08-23 20:47:41 -07:00
TcpConnector {
addrs,
2018-08-28 16:24:36 -07:00
host: Some(host),
addr: None,
2018-08-23 20:47:41 -07:00
stream: None,
}
}
}
impl Future for TcpConnector {
2018-08-28 16:24:36 -07:00
type Item = (ConnectionInfo, TcpStream);
2018-08-23 20:47:41 -07:00
type Error = ConnectorError;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
// connect
loop {
if let Some(new) = self.stream.as_mut() {
match new.poll() {
2018-08-28 16:24:36 -07:00
Ok(Async::Ready(sock)) => {
return Ok(Async::Ready((
ConnectionInfo {
host: self.host.take().unwrap(),
addr: self.addr.take().unwrap(),
},
sock,
)))
}
2018-08-23 20:47:41 -07:00
Ok(Async::NotReady) => return Ok(Async::NotReady),
Err(err) => {
if self.addrs.is_empty() {
return Err(ConnectorError::IoError(err));
}
}
}
}
// try to connect
let addr = self.addrs.pop_front().unwrap();
self.stream = Some(TcpStream::connect(&addr));
2018-08-28 16:24:36 -07:00
self.addr = Some(addr)
2018-08-23 20:47:41 -07:00
}
}
}