2020-03-05 00:25:24 +00:00
|
|
|
use futures::{sink::SinkExt, stream::StreamExt};
|
2018-12-18 18:04:31 +00:00
|
|
|
use native_tls::TlsConnector as NativeTlsConnector;
|
2020-03-05 00:25:24 +00:00
|
|
|
use tokio::io::{AsyncRead, AsyncWrite};
|
|
|
|
use tokio_tls::{TlsConnector, TlsStream};
|
|
|
|
use xmpp_parsers::Element;
|
2017-06-04 22:42:35 +00:00
|
|
|
|
2018-12-18 17:29:31 +00:00
|
|
|
use crate::xmpp_codec::Packet;
|
|
|
|
use crate::xmpp_stream::XMPPStream;
|
2020-03-05 00:25:24 +00:00
|
|
|
use crate::{Error, ProtocolError};
|
2017-06-04 22:42:35 +00:00
|
|
|
|
2018-08-02 17:58:19 +00:00
|
|
|
/// XMPP TLS XML namespace
|
2017-06-05 00:50:22 +00:00
|
|
|
pub const NS_XMPP_TLS: &str = "urn:ietf:params:xml:ns:xmpp-tls";
|
2017-06-04 22:42:35 +00:00
|
|
|
|
2020-03-05 00:25:24 +00:00
|
|
|
pub async fn starttls<S: AsyncRead + AsyncWrite + Unpin>(
|
|
|
|
mut xmpp_stream: XMPPStream<S>,
|
|
|
|
) -> Result<TlsStream<S>, Error> {
|
|
|
|
let nonza = Element::builder("starttls").ns(NS_XMPP_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(ProtocolError::NoTls.into());
|
|
|
|
}
|
2017-06-04 22:42:35 +00:00
|
|
|
}
|
|
|
|
}
|
2018-09-01 19:59:02 +00:00
|
|
|
|
2020-03-05 00:25:24 +00:00
|
|
|
let domain = xmpp_stream.jid.clone().domain();
|
|
|
|
let stream = xmpp_stream.into_inner();
|
|
|
|
let tls_stream = TlsConnector::from(NativeTlsConnector::builder().build().unwrap())
|
|
|
|
.connect(&domain, stream)
|
|
|
|
.await?;
|
2017-06-04 22:42:35 +00:00
|
|
|
|
2020-03-05 00:25:24 +00:00
|
|
|
Ok(tls_stream)
|
2017-06-04 22:42:35 +00:00
|
|
|
}
|