unstringify Error type

This commit is contained in:
Astro 2018-09-06 17:46:06 +02:00
commit e9d30f16c3
12 changed files with 279 additions and 167 deletions

View file

@ -13,9 +13,11 @@ use try_from::TryFrom;
use xmpp_codec::Packet;
use xmpp_stream::XMPPStream;
use stream_start::StreamStart;
use {Error, AuthError, ProtocolError};
const NS_XMPP_SASL: &str = "urn:ietf:params:xml:ns:xmpp-sasl";
pub struct ClientAuth<S: AsyncWrite> {
state: ClientAuthState<S>,
mechanism: Box<Mechanism>,
@ -29,7 +31,7 @@ enum ClientAuthState<S: AsyncWrite> {
}
impl<S: AsyncWrite> ClientAuth<S> {
pub fn new(stream: XMPPStream<S>, creds: Credentials) -> Result<Self, String> {
pub fn new(stream: XMPPStream<S>, creds: Credentials) -> Result<Self, Error> {
let mechs: Vec<Box<Mechanism>> = vec![
Box::new(Scram::<Sha256>::from_credentials(creds.clone()).unwrap()),
Box::new(Scram::<Sha1>::from_credentials(creds.clone()).unwrap()),
@ -40,7 +42,7 @@ impl<S: AsyncWrite> ClientAuth<S> {
let mech_names: Vec<String> =
match stream.stream_features.get_child("mechanisms", NS_XMPP_SASL) {
None =>
return Err("No auth mechanisms".to_owned()),
return Err(AuthError::NoMechanism.into()),
Some(mechs) =>
mechs.children()
.filter(|child| child.is("mechanism", NS_XMPP_SASL))
@ -53,13 +55,18 @@ impl<S: AsyncWrite> ClientAuth<S> {
let name = mech.name().to_owned();
if mech_names.iter().any(|name1| *name1 == name) {
// println!("SASL mechanism selected: {:?}", name);
let initial = mech.initial()?;
let initial = match mech.initial() {
Ok(initial) => initial,
Err(e) => return Err(AuthError::Sasl(e).into()),
};
let mut this = ClientAuth {
state: ClientAuthState::Invalid,
mechanism: mech,
};
let mechanism = XMPPMechanism::from_str(&name)
.map_err(|e| format!("{:?}", e))?;
let mechanism = match XMPPMechanism::from_str(&name) {
Ok(mechanism) => mechanism,
Err(e) => return Err(ProtocolError::Parsers(e).into()),
};
this.send(
stream,
Auth {
@ -71,7 +78,7 @@ impl<S: AsyncWrite> ClientAuth<S> {
}
}
Err("No supported SASL mechanism available".to_owned())
Err(AuthError::NoMechanism.into())
}
fn send<N: Into<Element>>(&mut self, stream: XMPPStream<S>, nonza: N) {
@ -83,7 +90,7 @@ impl<S: AsyncWrite> ClientAuth<S> {
impl<S: AsyncRead + AsyncWrite> Future for ClientAuth<S> {
type Item = XMPPStream<S>;
type Error = String;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let state = replace(&mut self.state, ClientAuthState::Invalid);
@ -100,13 +107,14 @@ impl<S: AsyncRead + AsyncWrite> Future for ClientAuth<S> {
Ok(Async::NotReady)
},
Err(e) =>
Err(format!("{}", e)),
Err(e.into()),
},
ClientAuthState::WaitRecv(mut stream) =>
match stream.poll() {
Ok(Async::Ready(Some(Packet::Stanza(stanza)))) => {
if let Ok(challenge) = Challenge::try_from(stanza.clone()) {
let response = self.mechanism.response(&challenge.data)?;
let response = self.mechanism.response(&challenge.data)
.map_err(AuthError::Sasl)?;
self.send(stream, Response { data: response });
self.poll()
} else if let Ok(_) = Success::try_from(stanza.clone()) {
@ -114,8 +122,7 @@ impl<S: AsyncRead + AsyncWrite> Future for ClientAuth<S> {
self.state = ClientAuthState::Start(start);
self.poll()
} else if let Ok(failure) = Failure::try_from(stanza) {
let e = format!("{:?}", failure.defined_condition);
Err(e)
Err(AuthError::Fail(failure.defined_condition).into())
} else {
Ok(Async::NotReady)
}
@ -129,7 +136,7 @@ impl<S: AsyncRead + AsyncWrite> Future for ClientAuth<S> {
Ok(Async::NotReady)
},
Err(e) =>
Err(format!("{}", e)),
Err(ProtocolError::Parser(e).into())
},
ClientAuthState::Start(mut start) =>
match start.poll() {
@ -140,7 +147,7 @@ impl<S: AsyncRead + AsyncWrite> Future for ClientAuth<S> {
Ok(Async::NotReady)
},
Err(e) =>
Err(format!("{}", e)),
Err(e.into())
},
ClientAuthState::Invalid =>
unreachable!(),

View file

@ -1,5 +1,4 @@
use std::mem::replace;
use std::error::Error;
use futures::{Future, Poll, Async, sink, Stream};
use tokio_io::{AsyncRead, AsyncWrite};
use xmpp_parsers::iq::{Iq, IqType};
@ -8,6 +7,7 @@ use try_from::TryFrom;
use xmpp_codec::Packet;
use xmpp_stream::XMPPStream;
use {Error, ProtocolError};
const NS_XMPP_BIND: &str = "urn:ietf:params:xml:ns:xmpp-bind";
const BIND_REQ_ID: &str = "resource-bind";
@ -42,7 +42,7 @@ impl<S: AsyncWrite> ClientBind<S> {
impl<S: AsyncRead + AsyncWrite> Future for ClientBind<S> {
type Item = XMPPStream<S>;
type Error = String;
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let state = replace(self, ClientBind::Invalid);
@ -61,7 +61,7 @@ impl<S: AsyncRead + AsyncWrite> Future for ClientBind<S> {
Ok(Async::NotReady)
},
Err(e) =>
Err(e.description().to_owned()),
Err(e.into())
}
},
ClientBind::WaitRecv(mut stream) => {
@ -80,7 +80,7 @@ impl<S: AsyncRead + AsyncWrite> Future for ClientBind<S> {
Ok(Async::Ready(stream))
},
_ =>
Err("resource bind response".to_owned()),
Err(ProtocolError::InvalidBindResponse.into()),
}
} else {
Ok(Async::NotReady)
@ -96,7 +96,7 @@ impl<S: AsyncRead + AsyncWrite> Future for ClientBind<S> {
Ok(Async::NotReady)
},
Err(e) =>
Err(e.description().to_owned()),
Err(e.into()),
}
},
ClientBind::Invalid =>

View file

@ -1,11 +1,11 @@
use std::mem::replace;
use std::str::FromStr;
use std::error::Error;
use std::error::Error as StdError;
use tokio_core::reactor::Handle;
use tokio_core::net::TcpStream;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_tls::TlsStream;
use futures::{future, Future, Stream, Poll, Async, Sink, StartSend, AsyncSink};
use futures::{Future, Stream, Poll, Async, Sink, StartSend, AsyncSink, done};
use minidom::Element;
use jid::{Jid, JidParseError};
use sasl::common::{Credentials, ChannelBinding};
@ -16,6 +16,7 @@ use super::xmpp_stream;
use super::starttls::{NS_XMPP_TLS, StartTlsClient};
use super::happy_eyeballs::Connecter;
use super::event::Event;
use super::{Error, ProtocolError};
mod auth;
use self::auth::ClientAuth;
@ -35,7 +36,7 @@ const NS_JABBER_CLIENT: &str = "jabber:client";
enum ClientState {
Invalid,
Disconnected,
Connecting(Box<Future<Item=XMPPStream, Error=String>>),
Connecting(Box<Future<Item=XMPPStream, Error=Error>>),
Connected(XMPPStream),
}
@ -50,47 +51,47 @@ impl Client {
let connect = Self::make_connect(jid.clone(), password.clone(), handle);
Ok(Client {
jid,
state: ClientState::Connecting(connect),
state: ClientState::Connecting(Box::new(connect)),
})
}
fn make_connect(jid: Jid, password: String, handle: Handle) -> Box<Future<Item=XMPPStream, Error=String>> {
fn make_connect(jid: Jid, password: String, handle: Handle) -> impl Future<Item=XMPPStream, Error=Error> {
let username = jid.node.as_ref().unwrap().to_owned();
let jid1 = jid.clone();
let jid2 = jid.clone();
let password = password;
let domain = match idna::domain_to_ascii(&jid.domain) {
Ok(domain) =>
domain,
Err(e) =>
return Box::new(future::err(format!("{:?}", e))),
};
Box::new(
Connecter::from_lookup(handle, &domain, "_xmpp-client._tcp", 5222)
.expect("Connector::from_lookup")
.and_then(move |tcp_stream|
xmpp_stream::XMPPStream::start(tcp_stream, jid1, NS_JABBER_CLIENT.to_owned())
.map_err(|e| format!("{}", e))
).and_then(|xmpp_stream| {
if Self::can_starttls(&xmpp_stream) {
Ok(Self::starttls(xmpp_stream))
} else {
Err("No STARTTLS".to_owned())
}
}).and_then(|starttls|
starttls
).and_then(|tls_stream|
XMPPStream::start(tls_stream, jid2, NS_JABBER_CLIENT.to_owned())
.map_err(|e| format!("{}", e))
).and_then(move |xmpp_stream| {
Self::auth(xmpp_stream, username, password).expect("auth")
}).and_then(|xmpp_stream| {
Self::bind(xmpp_stream)
}).and_then(|xmpp_stream| {
// println!("Bound to {}", xmpp_stream.jid);
Ok(xmpp_stream)
})
)
done(idna::domain_to_ascii(&jid.domain))
.map_err(|_| Error::Idna)
.and_then(|domain|
done(Connecter::from_lookup(handle, &domain, "_xmpp-client._tcp", 5222))
.map_err(Error::Domain)
)
.and_then(|connecter|
connecter
.map_err(Error::Connection)
).and_then(move |tcp_stream|
xmpp_stream::XMPPStream::start(tcp_stream, jid1, NS_JABBER_CLIENT.to_owned())
).and_then(|xmpp_stream| {
if Self::can_starttls(&xmpp_stream) {
Ok(Self::starttls(xmpp_stream))
} else {
Err(Error::Protocol(ProtocolError::NoTls))
}
}).and_then(|starttls|
// TODO: flatten?
starttls
).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)
}).and_then(|xmpp_stream| {
// println!("Bound to {}", xmpp_stream.jid);
Ok(xmpp_stream)
})
}
fn can_starttls<S>(stream: &xmpp_stream::XMPPStream<S>) -> bool {
@ -103,7 +104,7 @@ impl Client {
StartTlsClient::from_stream(stream)
}
fn auth<S: AsyncRead + AsyncWrite>(stream: xmpp_stream::XMPPStream<S>, username: String, password: String) -> Result<ClientAuth<S>, String> {
fn auth<S: AsyncRead + AsyncWrite>(stream: xmpp_stream::XMPPStream<S>, username: String, password: String) -> Result<ClientAuth<S>, Error> {
let creds = Credentials::default()
.with_username(username)
.with_password(password)
@ -118,14 +119,14 @@ impl Client {
impl Stream for Client {
type Item = Event;
type Error = String;
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let state = replace(&mut self.state, ClientState::Invalid);
match state {
ClientState::Invalid =>
Err("invalid client state".to_owned()),
Err(Error::InvalidState),
ClientState::Disconnected =>
Ok(Async::Ready(None)),
ClientState::Connecting(mut connect) => {
@ -148,7 +149,7 @@ impl Stream for Client {
Ok(Async::NotReady) => (),
Ok(Async::Ready(())) => (),
Err(e) =>
return Err(e.description().to_owned()),
return Err(Error::Io(e)),
};
// Poll stream
@ -168,7 +169,7 @@ impl Stream for Client {
Ok(Async::NotReady)
},
Err(e) =>
Err(e.description().to_owned()),
Err(e.into()),
}
},
}