xmpp-rs/tokio-xmpp/src/starttls.rs

39 lines
1.2 KiB
Rust
Raw Normal View History

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::{ns, 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
2020-03-15 23:34:46 +00:00
/// Performs `<starttls/>` on an XMPPStream and returns a binary
/// TlsStream.
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::TLS).build();
2020-03-05 00:25:24 +00:00
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
}