xmpp-rs-mirror/tokio-xmpp/src/happy_eyeballs.rs

68 lines
2.2 KiB
Rust
Raw Normal View History

2018-12-18 18:04:31 +00:00
use crate::{ConnecterError, Error};
use idna;
use log::debug;
2018-12-18 18:04:31 +00:00
use std::net::SocketAddr;
use tokio::net::TcpStream;
2020-03-05 00:25:24 +00:00
use trust_dns_resolver::{IntoName, TokioAsyncResolver};
pub async fn connect_to_host(domain: &str, port: u16) -> Result<TcpStream, Error> {
let ascii_domain = idna::domain_to_ascii(&domain).map_err(|_| Error::Idna)?;
if let Ok(ip) = ascii_domain.parse() {
return Ok(TcpStream::connect(&SocketAddr::new(ip, port)).await?);
}
let resolver = TokioAsyncResolver::tokio_from_system_conf().map_err(ConnecterError::Resolve)?;
2020-03-05 00:25:24 +00:00
let ips = resolver
.lookup_ip(ascii_domain)
2020-03-05 00:25:24 +00:00
.await
.map_err(ConnecterError::Resolve)?;
for ip in ips.iter() {
match TcpStream::connect(&SocketAddr::new(ip, port)).await {
Ok(stream) => return Ok(stream),
Err(_) => {}
}
}
Err(Error::Disconnected)
2018-09-06 22:12:00 +00:00
}
pub async fn connect_with_srv(
2020-03-05 00:25:24 +00:00
domain: &str,
srv: &str,
2018-09-01 19:59:02 +00:00
fallback_port: u16,
2020-03-05 00:25:24 +00:00
) -> Result<TcpStream, Error> {
let ascii_domain = idna::domain_to_ascii(&domain).map_err(|_| Error::Idna)?;
if let Ok(ip) = ascii_domain.parse() {
debug!("Attempting connection to {ip}:{fallback_port}");
2020-03-05 00:25:24 +00:00
return Ok(TcpStream::connect(&SocketAddr::new(ip, fallback_port)).await?);
2017-07-13 00:56:02 +00:00
}
2020-12-30 02:15:59 +00:00
let resolver = TokioAsyncResolver::tokio_from_system_conf().map_err(ConnecterError::Resolve)?;
2017-07-13 00:56:02 +00:00
let srv_domain = format!("{}.{}.", srv, ascii_domain)
.into_name()
.map_err(ConnecterError::Dns)?;
let srv_records = resolver.srv_lookup(srv_domain.clone()).await.ok();
2020-03-05 00:25:24 +00:00
match srv_records {
Some(lookup) => {
// TODO: sort lookup records by priority/weight
for srv in lookup.iter() {
debug!("Attempting connection to {srv_domain} {srv}");
match connect_to_host(&srv.target().to_ascii(), srv.port()).await {
2020-03-05 00:25:24 +00:00
Ok(stream) => return Ok(stream),
Err(_) => {}
2018-09-01 19:59:02 +00:00
}
2017-07-13 00:56:02 +00:00
}
2020-03-05 00:25:24 +00:00
Err(Error::Disconnected)
}
None => {
// SRV lookup error, retry with hostname
debug!("Attempting connection to {domain}:{fallback_port}");
connect_to_host(domain, fallback_port).await
2017-07-13 20:17:29 +00:00
}
2017-07-13 00:56:02 +00:00
}
}