Make Client and Component more unified, and connectors too
This commit is contained in:
parent
fde4c2b640
commit
311e7406f0
11 changed files with 338 additions and 183 deletions
173
tokio-xmpp/src/connect/dns.rs
Normal file
173
tokio-xmpp/src/connect/dns.rs
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
#[cfg(feature = "dns")]
|
||||
use futures::{future::select_ok, FutureExt};
|
||||
#[cfg(feature = "dns")]
|
||||
use hickory_resolver::{
|
||||
config::LookupIpStrategy, name_server::TokioConnectionProvider, IntoName, TokioAsyncResolver,
|
||||
};
|
||||
#[cfg(feature = "dns")]
|
||||
use log::debug;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::Error;
|
||||
|
||||
/// StartTLS XMPP server connection configuration
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum DnsConfig {
|
||||
/// Use SRV record to find server host
|
||||
#[cfg(feature = "dns")]
|
||||
UseSrv {
|
||||
/// Hostname to resolve
|
||||
host: String,
|
||||
/// TXT field eg. _xmpp-client._tcp
|
||||
srv: String,
|
||||
/// When SRV resolution fails what port to use
|
||||
fallback_port: u16,
|
||||
},
|
||||
|
||||
/// Manually define server host and port
|
||||
#[allow(unused)]
|
||||
#[cfg(feature = "dns")]
|
||||
NoSrv {
|
||||
/// Server host name
|
||||
host: String,
|
||||
/// Server port
|
||||
port: u16,
|
||||
},
|
||||
|
||||
/// Manually define IP: port (TODO: socket)
|
||||
#[allow(unused)]
|
||||
Addr {
|
||||
/// IP:port
|
||||
addr: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DnsConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
#[cfg(feature = "dns")]
|
||||
Self::UseSrv { host, .. } => write!(f, "{}", host),
|
||||
#[cfg(feature = "dns")]
|
||||
Self::NoSrv { host, port } => write!(f, "{}:{}", host, port),
|
||||
Self::Addr { addr } => write!(f, "{}", addr),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DnsConfig {
|
||||
/// Constructor for DnsConfig::UseSrv variant
|
||||
#[cfg(feature = "dns")]
|
||||
pub fn srv(host: &str, srv: &str, fallback_port: u16) -> Self {
|
||||
Self::UseSrv {
|
||||
host: host.to_string(),
|
||||
srv: srv.to_string(),
|
||||
fallback_port,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructor for the default SRV resolution strategy for clients
|
||||
#[cfg(feature = "dns")]
|
||||
pub fn srv_default_client(host: &str) -> Self {
|
||||
Self::UseSrv {
|
||||
host: host.to_string(),
|
||||
srv: "_xmpp-client._tcp".to_string(),
|
||||
fallback_port: 5222,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructor for DnsConfig::NoSrv variant
|
||||
#[cfg(feature = "dns")]
|
||||
pub fn no_srv(host: &str, port: u16) -> Self {
|
||||
Self::NoSrv {
|
||||
host: host.to_string(),
|
||||
port,
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructor for DnsConfig::Addr variant
|
||||
pub fn addr(addr: &str) -> Self {
|
||||
Self::Addr {
|
||||
addr: addr.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Try resolve the DnsConfig to a TcpStream
|
||||
pub async fn resolve(&self) -> Result<TcpStream, Error> {
|
||||
match self {
|
||||
#[cfg(feature = "dns")]
|
||||
Self::UseSrv {
|
||||
host,
|
||||
srv,
|
||||
fallback_port,
|
||||
} => Self::resolve_srv(host, srv, *fallback_port).await,
|
||||
#[cfg(feature = "dns")]
|
||||
Self::NoSrv { host, port } => Self::resolve_no_srv(host, *port).await,
|
||||
Self::Addr { addr } => {
|
||||
// TODO: Unix domain socket
|
||||
let addr: SocketAddr = addr.parse()?;
|
||||
return Ok(TcpStream::connect(&SocketAddr::new(addr.ip(), addr.port())).await?);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "dns")]
|
||||
async fn resolve_srv(host: &str, srv: &str, fallback_port: u16) -> Result<TcpStream, Error> {
|
||||
let ascii_domain = idna::domain_to_ascii(&host)?;
|
||||
|
||||
if let Ok(ip) = ascii_domain.parse() {
|
||||
debug!("Attempting connection to {ip}:{fallback_port}");
|
||||
return Ok(TcpStream::connect(&SocketAddr::new(ip, fallback_port)).await?);
|
||||
}
|
||||
|
||||
let resolver = TokioAsyncResolver::tokio_from_system_conf()?;
|
||||
|
||||
let srv_domain = format!("{}.{}.", srv, ascii_domain).into_name()?;
|
||||
let srv_records = resolver.srv_lookup(srv_domain.clone()).await.ok();
|
||||
|
||||
match srv_records {
|
||||
Some(lookup) => {
|
||||
// TODO: sort lookup records by priority/weight
|
||||
for srv in lookup.iter() {
|
||||
debug!("Attempting connection to {srv_domain} {srv}");
|
||||
if let Ok(stream) =
|
||||
Self::resolve_no_srv(&srv.target().to_ascii(), srv.port()).await
|
||||
{
|
||||
return Ok(stream);
|
||||
}
|
||||
}
|
||||
Err(Error::Disconnected)
|
||||
}
|
||||
None => {
|
||||
// SRV lookup error, retry with hostname
|
||||
debug!("Attempting connection to {host}:{fallback_port}");
|
||||
Self::resolve_no_srv(host, fallback_port).await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "dns")]
|
||||
async fn resolve_no_srv(host: &str, port: u16) -> Result<TcpStream, Error> {
|
||||
let ascii_domain = idna::domain_to_ascii(&host)?;
|
||||
|
||||
if let Ok(ip) = ascii_domain.parse() {
|
||||
return Ok(TcpStream::connect(&SocketAddr::new(ip, port)).await?);
|
||||
}
|
||||
|
||||
let (config, mut options) = hickory_resolver::system_conf::read_system_conf()?;
|
||||
options.ip_strategy = LookupIpStrategy::Ipv4AndIpv6;
|
||||
let resolver = TokioAsyncResolver::new(config, options, TokioConnectionProvider::default());
|
||||
|
||||
let ips = resolver.lookup_ip(ascii_domain).await?;
|
||||
|
||||
// Happy Eyeballs: connect to all records in parallel, return the
|
||||
// first to succeed
|
||||
select_ok(
|
||||
ips.into_iter()
|
||||
.map(|ip| TcpStream::connect(SocketAddr::new(ip, port)).boxed()),
|
||||
)
|
||||
.await
|
||||
.map(|(result, _)| result)
|
||||
.map_err(|_| Error::Disconnected)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,17 +1,7 @@
|
|||
//! `ServerConnector` provides streams for XMPP clients
|
||||
|
||||
#[cfg(feature = "dns")]
|
||||
use futures::{future::select_ok, FutureExt};
|
||||
#[cfg(feature = "dns")]
|
||||
use hickory_resolver::{
|
||||
config::LookupIpStrategy, name_server::TokioConnectionProvider, IntoName, TokioAsyncResolver,
|
||||
};
|
||||
#[cfg(feature = "dns")]
|
||||
use log::debug;
|
||||
use sasl::common::ChannelBinding;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio::net::TcpStream;
|
||||
use xmpp_parsers::jid::Jid;
|
||||
|
||||
use crate::proto::XmppStream;
|
||||
|
|
@ -19,8 +9,16 @@ use crate::Error;
|
|||
|
||||
#[cfg(feature = "starttls")]
|
||||
pub mod starttls;
|
||||
#[cfg(feature = "starttls")]
|
||||
pub use starttls::StartTlsServerConnector;
|
||||
|
||||
#[cfg(feature = "insecure-tcp")]
|
||||
pub mod tcp;
|
||||
#[cfg(feature = "insecure-tcp")]
|
||||
pub use tcp::TcpServerConnector;
|
||||
|
||||
mod dns;
|
||||
pub use dns::DnsConfig;
|
||||
|
||||
/// trait returned wrapped in XmppStream by ServerConnector
|
||||
pub trait AsyncReadAndWrite: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
|
|
@ -47,78 +45,3 @@ pub trait ServerConnector: Clone + core::fmt::Debug + Send + Unpin + 'static {
|
|||
Ok(ChannelBinding::None)
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple wrapper to build [`TcpStream`]
|
||||
pub struct Tcp;
|
||||
|
||||
impl Tcp {
|
||||
/// Connect directly to an IP/Port combo
|
||||
pub async fn connect(ip: IpAddr, port: u16) -> Result<TcpStream, Error> {
|
||||
Ok(TcpStream::connect(&SocketAddr::new(ip, port)).await?)
|
||||
}
|
||||
|
||||
/// Connect over TCP, resolving A/AAAA records (happy eyeballs)
|
||||
#[cfg(feature = "dns")]
|
||||
pub async fn resolve(domain: &str, port: u16) -> Result<TcpStream, Error> {
|
||||
let ascii_domain = idna::domain_to_ascii(&domain)?;
|
||||
|
||||
if let Ok(ip) = ascii_domain.parse() {
|
||||
return Ok(TcpStream::connect(&SocketAddr::new(ip, port)).await?);
|
||||
}
|
||||
|
||||
let (config, mut options) = hickory_resolver::system_conf::read_system_conf()?;
|
||||
options.ip_strategy = LookupIpStrategy::Ipv4AndIpv6;
|
||||
let resolver = TokioAsyncResolver::new(config, options, TokioConnectionProvider::default());
|
||||
|
||||
let ips = resolver.lookup_ip(ascii_domain).await?;
|
||||
|
||||
// Happy Eyeballs: connect to all records in parallel, return the
|
||||
// first to succeed
|
||||
select_ok(
|
||||
ips.into_iter()
|
||||
.map(|ip| TcpStream::connect(SocketAddr::new(ip, port)).boxed()),
|
||||
)
|
||||
.await
|
||||
.map(|(result, _)| result)
|
||||
.map_err(|_| Error::Disconnected)
|
||||
}
|
||||
|
||||
/// Connect over TCP, resolving SRV records
|
||||
#[cfg(feature = "dns")]
|
||||
pub async fn resolve_with_srv(
|
||||
domain: &str,
|
||||
srv: &str,
|
||||
fallback_port: u16,
|
||||
) -> Result<TcpStream, Error> {
|
||||
let ascii_domain = idna::domain_to_ascii(&domain)?;
|
||||
|
||||
if let Ok(ip) = ascii_domain.parse() {
|
||||
debug!("Attempting connection to {ip}:{fallback_port}");
|
||||
return Ok(TcpStream::connect(&SocketAddr::new(ip, fallback_port)).await?);
|
||||
}
|
||||
|
||||
let resolver = TokioAsyncResolver::tokio_from_system_conf()?;
|
||||
|
||||
let srv_domain = format!("{}.{}.", srv, ascii_domain).into_name()?;
|
||||
let srv_records = resolver.srv_lookup(srv_domain.clone()).await.ok();
|
||||
|
||||
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 Self::resolve(&srv.target().to_ascii(), srv.port()).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
Err(Error::Disconnected)
|
||||
}
|
||||
None => {
|
||||
// SRV lookup error, retry with hostname
|
||||
debug!("Attempting connection to {domain}:{fallback_port}");
|
||||
Self::resolve(domain, fallback_port).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,40 +37,31 @@ use tokio::{
|
|||
use xmpp_parsers::{jid::Jid, ns};
|
||||
|
||||
use crate::{
|
||||
connect::{ServerConnector, ServerConnectorError, Tcp},
|
||||
connect::{DnsConfig, ServerConnector, ServerConnectorError},
|
||||
error::{Error, ProtocolError},
|
||||
proto::{Packet, XmppStream},
|
||||
AsyncClient,
|
||||
AsyncClient, Component,
|
||||
};
|
||||
|
||||
/// AsyncClient that connects over StartTls
|
||||
pub type StartTlsAsyncClient = AsyncClient<ServerConfig>;
|
||||
/// Client that connects over StartTls
|
||||
pub type StartTlsClient = AsyncClient<StartTlsServerConnector>;
|
||||
/// Component that connects over StartTls
|
||||
pub type StartTlsComponent = Component<StartTlsServerConnector>;
|
||||
|
||||
/// StartTLS XMPP server connection configuration
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ServerConfig {
|
||||
/// Use SRV record to find server host
|
||||
UseSrv,
|
||||
#[allow(unused)]
|
||||
/// Manually define server host and port
|
||||
Manual {
|
||||
/// Server host name
|
||||
host: String,
|
||||
/// Server port
|
||||
port: u16,
|
||||
},
|
||||
/// Connect via TCP+StartTLS to an XMPP server
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StartTlsServerConnector(pub DnsConfig);
|
||||
|
||||
impl From<DnsConfig> for StartTlsServerConnector {
|
||||
fn from(dns_config: DnsConfig) -> StartTlsServerConnector {
|
||||
Self(dns_config)
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerConnector for ServerConfig {
|
||||
impl ServerConnector for StartTlsServerConnector {
|
||||
type Stream = TlsStream<TcpStream>;
|
||||
async fn connect(&self, jid: &Jid, ns: &str) -> Result<XmppStream<Self::Stream>, Error> {
|
||||
// TCP connection
|
||||
let tcp_stream = match self {
|
||||
ServerConfig::UseSrv => {
|
||||
Tcp::resolve_with_srv(jid.domain().as_str(), "_xmpp-client._tcp", 5222).await?
|
||||
}
|
||||
ServerConfig::Manual { host, port } => Tcp::resolve(host.as_str(), *port).await?,
|
||||
};
|
||||
let tcp_stream = self.0.resolve().await?;
|
||||
|
||||
// Unencryped XmppStream
|
||||
let xmpp_stream = XmppStream::start(tcp_stream, jid.clone(), ns.to_owned()).await?;
|
||||
|
|
|
|||
|
|
@ -1,44 +1,37 @@
|
|||
//! `starttls::ServerConfig` provides a `ServerConnector` for starttls connections
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::{connect::ServerConnector, proto::XmppStream, Component, Error};
|
||||
use crate::connect::DnsConfig;
|
||||
use crate::{connect::ServerConnector, proto::XmppStream, AsyncClient, Component, Error};
|
||||
|
||||
/// Component that connects over TCP
|
||||
pub type TcpComponent = Component<TcpServerConnector>;
|
||||
|
||||
/// Client that connects over TCP
|
||||
pub type TcpClient = AsyncClient<TcpServerConnector>;
|
||||
|
||||
/// Connect via insecure plaintext TCP to an XMPP server
|
||||
/// This should only be used over localhost or otherwise when you know what you are doing
|
||||
/// Probably mostly useful for Components
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TcpServerConnector(Arc<String>);
|
||||
pub struct TcpServerConnector(pub DnsConfig);
|
||||
|
||||
impl TcpServerConnector {
|
||||
/// Create a new connector with the given address
|
||||
pub fn new(addr: String) -> Self {
|
||||
Self(addr.into())
|
||||
impl From<DnsConfig> for TcpServerConnector {
|
||||
fn from(dns_config: DnsConfig) -> TcpServerConnector {
|
||||
Self(dns_config)
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerConnector for TcpServerConnector {
|
||||
type Stream = TcpStream;
|
||||
|
||||
async fn connect(
|
||||
&self,
|
||||
jid: &xmpp_parsers::jid::Jid,
|
||||
ns: &str,
|
||||
) -> Result<XmppStream<Self::Stream>, Error> {
|
||||
let stream = TcpStream::connect(&*self.0)
|
||||
.await
|
||||
.map_err(|e| crate::Error::Io(e))?;
|
||||
let stream = self.0.resolve().await?;
|
||||
Ok(XmppStream::start(stream, jid.clone(), ns.to_owned()).await?)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component<TcpServerConnector> {
|
||||
/// Start a new XMPP component
|
||||
pub async fn new(jid: &str, password: &str, server: String) -> Result<Self, Error> {
|
||||
Self::new_with_connector(jid, password, TcpServerConnector::new(server)).await
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue