DNS/TLS deps are now optional, component now also uses ServerConnector
This commit is contained in:
parent
e784b15402
commit
733d005f51
17 changed files with 440 additions and 337 deletions
35
tokio-xmpp/src/starttls/client.rs
Normal file
35
tokio-xmpp/src/starttls/client.rs
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
use std::str::FromStr;
|
||||
|
||||
use xmpp_parsers::Jid;
|
||||
|
||||
use crate::{AsyncClient, AsyncConfig, Error, SimpleClient};
|
||||
|
||||
use super::ServerConfig;
|
||||
|
||||
impl AsyncClient<ServerConfig> {
|
||||
/// Start a new XMPP client
|
||||
///
|
||||
/// Start polling the returned instance so that it will connect
|
||||
/// and yield events.
|
||||
pub fn new<J: Into<Jid>, P: Into<String>>(jid: J, password: P) -> Self {
|
||||
let config = AsyncConfig {
|
||||
jid: jid.into(),
|
||||
password: password.into(),
|
||||
server: ServerConfig::UseSrv,
|
||||
};
|
||||
Self::new_with_config(config)
|
||||
}
|
||||
}
|
||||
|
||||
impl SimpleClient<ServerConfig> {
|
||||
/// Start a new XMPP client and wait for a usable session
|
||||
pub async fn new<P: Into<String>>(jid: &str, password: P) -> Result<Self, Error> {
|
||||
let jid = Jid::from_str(jid)?;
|
||||
Self::new_with_jid(jid, password.into()).await
|
||||
}
|
||||
|
||||
/// Start a new client given that the JID is already parsed.
|
||||
pub async fn new_with_jid(jid: Jid, password: String) -> Result<Self, Error> {
|
||||
Self::new_with_jid_connector(ServerConfig::UseSrv, jid, password).await
|
||||
}
|
||||
}
|
||||
105
tokio-xmpp/src/starttls/error.rs
Normal file
105
tokio-xmpp/src/starttls/error.rs
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
use hickory_resolver::{error::ResolveError, proto::error::ProtoError};
|
||||
#[cfg(feature = "tls-native")]
|
||||
use native_tls::Error as TlsError;
|
||||
use std::borrow::Cow;
|
||||
use std::error::Error as StdError;
|
||||
use std::fmt;
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
use tokio_rustls::rustls::client::InvalidDnsNameError;
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
use tokio_rustls::rustls::Error as TlsError;
|
||||
|
||||
/// Top-level error type
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// Error resolving DNS and establishing a connection
|
||||
Connection(ConnectorError),
|
||||
/// DNS label conversion error, no details available from module
|
||||
/// `idna`
|
||||
Idna,
|
||||
/// TLS error
|
||||
Tls(TlsError),
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
/// DNS name parsing error
|
||||
DnsNameError(InvalidDnsNameError),
|
||||
/// tokio-xmpp error
|
||||
TokioXMPP(crate::error::Error),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
|
||||
match self {
|
||||
Error::Connection(e) => write!(fmt, "connection error: {}", e),
|
||||
Error::Idna => write!(fmt, "IDNA error"),
|
||||
Error::Tls(e) => write!(fmt, "TLS error: {}", e),
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
Error::DnsNameError(e) => write!(fmt, "DNS name error: {}", e),
|
||||
Error::TokioXMPP(e) => write!(fmt, "TokioXMPP error: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StdError for Error {}
|
||||
|
||||
impl From<crate::error::Error> for Error {
|
||||
fn from(e: crate::error::Error) -> Self {
|
||||
Error::TokioXMPP(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ConnectorError> for Error {
|
||||
fn from(e: ConnectorError) -> Self {
|
||||
Error::Connection(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TlsError> for Error {
|
||||
fn from(e: TlsError) -> Self {
|
||||
Error::Tls(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
impl From<InvalidDnsNameError> for Error {
|
||||
fn from(e: InvalidDnsNameError) -> Self {
|
||||
Error::DnsNameError(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// XML parse error wrapper type
|
||||
#[derive(Debug)]
|
||||
pub struct ParseError(pub Cow<'static, str>);
|
||||
|
||||
impl StdError for ParseError {
|
||||
fn description(&self) -> &str {
|
||||
self.0.as_ref()
|
||||
}
|
||||
fn cause(&self) -> Option<&dyn StdError> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Error establishing connection
|
||||
#[derive(Debug)]
|
||||
pub enum ConnectorError {
|
||||
/// All attempts failed, no error available
|
||||
AllFailed,
|
||||
/// DNS protocol error
|
||||
Dns(ProtoError),
|
||||
/// DNS resolution error
|
||||
Resolve(ResolveError),
|
||||
}
|
||||
|
||||
impl StdError for ConnectorError {}
|
||||
|
||||
impl std::fmt::Display for ConnectorError {
|
||||
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
|
||||
write!(fmt, "{:?}", self)
|
||||
}
|
||||
}
|
||||
71
tokio-xmpp/src/starttls/happy_eyeballs.rs
Normal file
71
tokio-xmpp/src/starttls/happy_eyeballs.rs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
use super::error::{ConnectorError, Error};
|
||||
use hickory_resolver::{IntoName, TokioAsyncResolver};
|
||||
use idna;
|
||||
use log::debug;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
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
|
||||
.map_err(|e| Error::from(crate::Error::Io(e)))?);
|
||||
}
|
||||
|
||||
let resolver = TokioAsyncResolver::tokio_from_system_conf().map_err(ConnectorError::Resolve)?;
|
||||
|
||||
let ips = resolver
|
||||
.lookup_ip(ascii_domain)
|
||||
.await
|
||||
.map_err(ConnectorError::Resolve)?;
|
||||
for ip in ips.iter() {
|
||||
match TcpStream::connect(&SocketAddr::new(ip, port)).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
Err(crate::Error::Disconnected.into())
|
||||
}
|
||||
|
||||
pub async fn connect_with_srv(
|
||||
domain: &str,
|
||||
srv: &str,
|
||||
fallback_port: u16,
|
||||
) -> 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}");
|
||||
return Ok(TcpStream::connect(&SocketAddr::new(ip, fallback_port))
|
||||
.await
|
||||
.map_err(|e| Error::from(crate::Error::Io(e)))?);
|
||||
}
|
||||
|
||||
let resolver = TokioAsyncResolver::tokio_from_system_conf().map_err(ConnectorError::Resolve)?;
|
||||
|
||||
let srv_domain = format!("{}.{}.", srv, ascii_domain)
|
||||
.into_name()
|
||||
.map_err(ConnectorError::Dns)?;
|
||||
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 connect_to_host(&srv.target().to_ascii(), srv.port()).await {
|
||||
Ok(stream) => return Ok(stream),
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
Err(crate::Error::Disconnected.into())
|
||||
}
|
||||
None => {
|
||||
// SRV lookup error, retry with hostname
|
||||
debug!("Attempting connection to {domain}:{fallback_port}");
|
||||
connect_to_host(domain, fallback_port).await
|
||||
}
|
||||
}
|
||||
}
|
||||
168
tokio-xmpp/src/starttls/mod.rs
Normal file
168
tokio-xmpp/src/starttls/mod.rs
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
//! `starttls::ServerConfig` provides a `ServerConnector` for starttls connections
|
||||
|
||||
use futures::{sink::SinkExt, stream::StreamExt};
|
||||
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
use {
|
||||
std::sync::Arc,
|
||||
tokio_rustls::{
|
||||
client::TlsStream,
|
||||
rustls::{ClientConfig, OwnedTrustAnchor, RootCertStore, ServerName},
|
||||
TlsConnector,
|
||||
},
|
||||
webpki_roots,
|
||||
};
|
||||
|
||||
#[cfg(feature = "tls-native")]
|
||||
use {
|
||||
native_tls::TlsConnector as NativeTlsConnector,
|
||||
tokio_native_tls::{TlsConnector, TlsStream},
|
||||
};
|
||||
|
||||
use sasl::common::ChannelBinding;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncWrite},
|
||||
net::TcpStream,
|
||||
};
|
||||
use xmpp_parsers::{ns, Element, Jid};
|
||||
|
||||
use crate::{connect::ServerConnector, xmpp_codec::Packet};
|
||||
use crate::{connect::ServerConnectorError, xmpp_stream::XMPPStream};
|
||||
|
||||
use self::error::Error;
|
||||
use self::happy_eyeballs::{connect_to_host, connect_with_srv};
|
||||
|
||||
mod client;
|
||||
mod error;
|
||||
mod happy_eyeballs;
|
||||
|
||||
/// 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,
|
||||
},
|
||||
}
|
||||
|
||||
impl ServerConnectorError for Error {}
|
||||
|
||||
impl ServerConnector for ServerConfig {
|
||||
type Stream = TlsStream<TcpStream>;
|
||||
type Error = Error;
|
||||
async fn connect(&self, jid: &Jid, ns: &str) -> Result<XMPPStream<Self::Stream>, Error> {
|
||||
// TCP connection
|
||||
let tcp_stream = match self {
|
||||
ServerConfig::UseSrv => {
|
||||
connect_with_srv(jid.domain_str(), "_xmpp-client._tcp", 5222).await?
|
||||
}
|
||||
ServerConfig::Manual { host, port } => connect_to_host(host.as_str(), *port).await?,
|
||||
};
|
||||
|
||||
// Unencryped XMPPStream
|
||||
let xmpp_stream = XMPPStream::start(tcp_stream, jid.clone(), ns.to_owned()).await?;
|
||||
|
||||
if xmpp_stream.stream_features.can_starttls() {
|
||||
// TlsStream
|
||||
let tls_stream = starttls(xmpp_stream).await?;
|
||||
// Encrypted XMPPStream
|
||||
Ok(XMPPStream::start(tls_stream, jid.clone(), ns.to_owned()).await?)
|
||||
} else {
|
||||
return Err(crate::Error::Protocol(crate::ProtocolError::NoTls).into());
|
||||
}
|
||||
}
|
||||
|
||||
fn channel_binding(
|
||||
#[allow(unused_variables)] stream: &Self::Stream,
|
||||
) -> Result<sasl::common::ChannelBinding, Error> {
|
||||
#[cfg(feature = "tls-native")]
|
||||
{
|
||||
log::warn!("tls-native doesn’t support channel binding, please use tls-rust if you want this feature!");
|
||||
Ok(ChannelBinding::None)
|
||||
}
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
{
|
||||
let (_, connection) = stream.get_ref();
|
||||
Ok(match connection.protocol_version() {
|
||||
// TODO: Add support for TLS 1.2 and earlier.
|
||||
Some(tokio_rustls::rustls::ProtocolVersion::TLSv1_3) => {
|
||||
let data = vec![0u8; 32];
|
||||
let data = connection.export_keying_material(
|
||||
data,
|
||||
b"EXPORTER-Channel-Binding",
|
||||
None,
|
||||
)?;
|
||||
ChannelBinding::TlsExporter(data)
|
||||
}
|
||||
_ => ChannelBinding::None,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tls-native")]
|
||||
async fn get_tls_stream<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
xmpp_stream: XMPPStream<S>,
|
||||
) -> Result<TlsStream<S>, Error> {
|
||||
let domain = xmpp_stream.jid.domain_str().to_owned();
|
||||
let stream = xmpp_stream.into_inner();
|
||||
let tls_stream = TlsConnector::from(NativeTlsConnector::builder().build().unwrap())
|
||||
.connect(&domain, stream)
|
||||
.await?;
|
||||
Ok(tls_stream)
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
|
||||
async fn get_tls_stream<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
xmpp_stream: XMPPStream<S>,
|
||||
) -> Result<TlsStream<S>, Error> {
|
||||
let domain = xmpp_stream.jid.domain_str().to_owned();
|
||||
let domain = ServerName::try_from(domain.as_str())?;
|
||||
let stream = xmpp_stream.into_inner();
|
||||
let mut root_store = RootCertStore::empty();
|
||||
root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
|
||||
OwnedTrustAnchor::from_subject_spki_name_constraints(
|
||||
ta.subject,
|
||||
ta.spki,
|
||||
ta.name_constraints,
|
||||
)
|
||||
}));
|
||||
let config = ClientConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth();
|
||||
let tls_stream = TlsConnector::from(Arc::new(config))
|
||||
.connect(domain, stream)
|
||||
.await
|
||||
.map_err(|e| Error::from(crate::Error::Io(e)))?;
|
||||
Ok(tls_stream)
|
||||
}
|
||||
|
||||
/// Performs `<starttls/>` on an XMPPStream and returns a binary
|
||||
/// TlsStream.
|
||||
pub async fn starttls<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
mut xmpp_stream: XMPPStream<S>,
|
||||
) -> Result<TlsStream<S>, Error> {
|
||||
let nonza = Element::builder("starttls", ns::TLS).build();
|
||||
let packet = Packet::Stanza(nonza);
|
||||
xmpp_stream.send(packet).await?;
|
||||
|
||||
loop {
|
||||
match xmpp_stream.next().await {
|
||||
Some(Ok(Packet::Stanza(ref stanza))) if stanza.name() == "proceed" => break,
|
||||
Some(Ok(Packet::Text(_))) => {}
|
||||
Some(Err(e)) => return Err(e.into()),
|
||||
_ => {
|
||||
return Err(crate::Error::Protocol(crate::ProtocolError::NoTls).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get_tls_stream(xmpp_stream).await
|
||||
}
|
||||
Loading…
Reference in a new issue