xmpp-rs/tokio-xmpp/src/client/mod.rs

232 lines
7.8 KiB
Rust
Raw Normal View History

2018-12-18 18:04:31 +00:00
use futures::{done, Async, AsyncSink, Future, Poll, Sink, StartSend, Stream};
use idna;
use sasl::common::{ChannelBinding, Credentials};
2017-06-20 19:26:51 +00:00
use std::mem::replace;
use std::str::FromStr;
2018-09-01 19:59:02 +00:00
use tokio::net::TcpStream;
2017-06-20 19:26:51 +00:00
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_tls::TlsStream;
use xmpp_parsers::{Jid, JidParseError};
2017-06-20 19:26:51 +00:00
2018-12-18 18:04:31 +00:00
use super::event::Event;
use super::happy_eyeballs::Connecter;
use super::starttls::{StartTlsClient, NS_XMPP_TLS};
2017-06-20 19:26:51 +00:00
use super::xmpp_codec::Packet;
use super::xmpp_stream;
2018-09-06 15:46:06 +00:00
use super::{Error, ProtocolError};
2017-06-20 19:26:51 +00:00
mod auth;
2017-07-18 20:54:10 +00:00
use self::auth::ClientAuth;
2017-06-20 19:26:51 +00:00
mod bind;
2017-07-18 20:54:10 +00:00
use self::bind::ClientBind;
2017-06-20 19:26:51 +00:00
2018-08-02 17:58:19 +00:00
/// XMPP client connection and state
2017-06-20 19:26:51 +00:00
pub struct Client {
state: ClientState,
}
type XMPPStream = xmpp_stream::XMPPStream<TlsStream<TcpStream>>;
2017-07-18 23:02:45 +00:00
const NS_JABBER_CLIENT: &str = "jabber:client";
2017-06-20 19:26:51 +00:00
enum ClientState {
Invalid,
Disconnected,
Connecting(Box<dyn Future<Item = XMPPStream, Error = Error>>),
2017-06-20 19:26:51 +00:00
Connected(XMPPStream),
}
impl Client {
2018-08-02 17:58:19 +00:00
/// Start a new XMPP client
///
/// Start polling the returned instance so that it will connect
/// and yield events.
2018-09-01 19:59:02 +00:00
pub fn new(jid: &str, password: &str) -> Result<Self, JidParseError> {
2018-08-02 18:10:26 +00:00
let jid = Jid::from_str(jid)?;
let client = Self::new_with_jid(jid, password);
Ok(client)
}
/// Start a new client given that the JID is already parsed.
pub fn new_with_jid(jid: Jid, password: &str) -> Self {
2017-06-20 19:26:51 +00:00
let password = password.to_owned();
let connect = Self::make_connect(jid, password.clone());
let client = Client {
2018-09-06 15:46:06 +00:00
state: ClientState::Connecting(Box::new(connect)),
};
client
2017-06-20 19:26:51 +00:00
}
2018-12-18 18:04:31 +00:00
fn make_connect(jid: Jid, password: String) -> impl Future<Item = XMPPStream, Error = Error> {
2019-09-08 19:28:44 +00:00
let username = jid.clone().node().unwrap();
2017-07-18 23:02:45 +00:00
let jid1 = jid.clone();
let jid2 = jid.clone();
2017-06-20 19:26:51 +00:00
let password = password;
2019-09-08 19:28:44 +00:00
done(idna::domain_to_ascii(&jid.domain()))
2018-09-06 15:46:06 +00:00
.map_err(|_| Error::Idna)
2018-12-18 18:04:31 +00:00
.and_then(|domain| {
done(Connecter::from_lookup(
&domain,
Some("_xmpp-client._tcp"),
5222,
))
})
.flatten()
2018-12-18 18:04:31 +00:00
.and_then(move |tcp_stream| {
xmpp_stream::XMPPStream::start(tcp_stream, jid1, NS_JABBER_CLIENT.to_owned())
})
.and_then(|xmpp_stream| {
2018-09-06 15:46:06 +00:00
if Self::can_starttls(&xmpp_stream) {
Ok(Self::starttls(xmpp_stream))
} else {
Err(Error::Protocol(ProtocolError::NoTls))
}
2018-12-18 18:04:31 +00:00
})
.flatten()
.and_then(|tls_stream| XMPPStream::start(tls_stream, jid2, NS_JABBER_CLIENT.to_owned()))
.and_then(
move |xmpp_stream| done(Self::auth(xmpp_stream, username, password)), // TODO: flatten?
)
.and_then(|auth| auth)
.and_then(|xmpp_stream| Self::bind(xmpp_stream))
2018-09-06 15:46:06 +00:00
.and_then(|xmpp_stream| {
// println!("Bound to {}", xmpp_stream.jid);
Ok(xmpp_stream)
})
2017-06-20 19:26:51 +00:00
}
fn can_starttls<S>(stream: &xmpp_stream::XMPPStream<S>) -> bool {
2018-12-18 18:04:31 +00:00
stream
.stream_features
.get_child("starttls", NS_XMPP_TLS)
2017-06-20 19:26:51 +00:00
.is_some()
}
2018-12-18 18:04:31 +00:00
fn starttls<S: AsyncRead + AsyncWrite>(
stream: xmpp_stream::XMPPStream<S>,
) -> StartTlsClient<S> {
2017-06-20 19:26:51 +00:00
StartTlsClient::from_stream(stream)
}
2018-12-20 19:39:01 +00:00
fn auth<S: AsyncRead + AsyncWrite + 'static>(
2018-12-18 18:04:31 +00:00
stream: xmpp_stream::XMPPStream<S>,
username: String,
password: String,
) -> Result<ClientAuth<S>, Error> {
2017-06-20 19:26:51 +00:00
let creds = Credentials::default()
.with_username(username)
.with_password(password)
.with_channel_binding(ChannelBinding::None);
ClientAuth::new(stream, creds)
}
fn bind<S: AsyncWrite>(stream: xmpp_stream::XMPPStream<S>) -> ClientBind<S> {
ClientBind::new(stream)
}
/// Get the client's bound JID (the one reported by the XMPP
/// server).
pub fn bound_jid(&self) -> Option<&Jid> {
match self.state {
ClientState::Connected(ref stream) => Some(&stream.jid),
_ => None,
}
}
2017-06-20 19:26:51 +00:00
}
impl Stream for Client {
type Item = Event;
2018-09-06 15:46:06 +00:00
type Error = Error;
2017-06-20 19:26:51 +00:00
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let state = replace(&mut self.state, ClientState::Invalid);
match state {
2018-12-18 18:04:31 +00:00
ClientState::Invalid => Err(Error::InvalidState),
ClientState::Disconnected => Ok(Async::Ready(None)),
ClientState::Connecting(mut connect) => match connect.poll() {
Ok(Async::Ready(stream)) => {
let jid = stream.jid.clone();
2018-12-18 18:04:31 +00:00
self.state = ClientState::Connected(stream);
Ok(Async::Ready(Some(Event::Online(jid))))
2018-12-18 18:04:31 +00:00
}
Ok(Async::NotReady) => {
self.state = ClientState::Connecting(connect);
Ok(Async::NotReady)
2017-06-20 19:26:51 +00:00
}
2018-12-18 18:04:31 +00:00
Err(e) => Err(e),
2017-06-20 19:26:51 +00:00
},
ClientState::Connected(mut stream) => {
// Poll sink
match stream.poll_complete() {
Ok(Async::NotReady) => (),
Ok(Async::Ready(())) => (),
2018-12-18 18:04:31 +00:00
Err(e) => return Err(e)?,
};
// Poll stream
2017-06-20 19:26:51 +00:00
match stream.poll() {
Ok(Async::Ready(None)) => {
// EOF
self.state = ClientState::Disconnected;
Ok(Async::Ready(Some(Event::Disconnected)))
2018-12-18 18:04:31 +00:00
}
2017-06-20 19:26:51 +00:00
Ok(Async::Ready(Some(Packet::Stanza(stanza)))) => {
2019-01-26 20:07:15 +00:00
// Receive stanza
2017-06-20 19:26:51 +00:00
self.state = ClientState::Connected(stream);
Ok(Async::Ready(Some(Event::Stanza(stanza))))
2018-12-18 18:04:31 +00:00
}
2019-01-26 20:07:15 +00:00
Ok(Async::Ready(Some(Packet::Text(_)))) => {
// Ignore text between stanzas
Ok(Async::NotReady)
}
Ok(Async::Ready(Some(Packet::StreamStart(_)))) => {
// <stream:stream>
Err(ProtocolError::InvalidStreamStart.into())
}
Ok(Async::Ready(Some(Packet::StreamEnd))) => {
// End of stream: </stream:stream>
Ok(Async::Ready(None))
}
Ok(Async::NotReady) => {
// Try again later
2017-06-20 19:26:51 +00:00
self.state = ClientState::Connected(stream);
Ok(Async::NotReady)
2018-12-18 18:04:31 +00:00
}
Err(e) => Err(e)?,
2017-06-20 19:26:51 +00:00
}
2018-12-18 18:04:31 +00:00
}
2017-06-20 19:26:51 +00:00
}
}
}
impl Sink for Client {
type SinkItem = Packet;
2018-09-06 16:20:05 +00:00
type SinkError = Error;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
match self.state {
ClientState::Connected(ref mut stream) => Ok(stream.start_send(item)?),
_ => Ok(AsyncSink::NotReady(item)),
}
}
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
2017-07-20 22:19:08 +00:00
match self.state {
2018-12-18 18:04:31 +00:00
ClientState::Connected(ref mut stream) => stream.poll_complete().map_err(|e| e.into()),
_ => Ok(Async::Ready(())),
}
}
/// This closes the inner TCP stream.
///
/// To synchronize your shutdown with the server side, you should
/// first send `Packet::StreamEnd` and wait for the end of the
/// incoming stream before closing the connection.
fn close(&mut self) -> Poll<(), Self::SinkError> {
match self.state {
ClientState::Connected(ref mut stream) => stream.close().map_err(|e| e.into()),
_ => Ok(Async::Ready(())),
}
}
}