impl stream for client

This commit is contained in:
Astro 2017-06-20 21:26:51 +02:00
commit 1e2672ba50
7 changed files with 254 additions and 70 deletions

174
src/client/auth.rs Normal file
View file

@ -0,0 +1,174 @@
use std::mem::replace;
use futures::*;
use futures::sink;
use tokio_io::{AsyncRead, AsyncWrite};
use xml;
use sasl::common::Credentials;
use sasl::common::scram::*;
use sasl::client::Mechanism;
use sasl::client::mechanisms::*;
use serialize::base64::{self, ToBase64, FromBase64};
use xmpp_codec::*;
use xmpp_stream::*;
use stream_start::*;
const NS_XMPP_SASL: &str = "urn:ietf:params:xml:ns:xmpp-sasl";
pub struct ClientAuth<S: AsyncWrite> {
state: ClientAuthState<S>,
mechanism: Box<Mechanism>,
}
enum ClientAuthState<S: AsyncWrite> {
WaitSend(sink::Send<XMPPStream<S>>),
WaitRecv(XMPPStream<S>),
Start(StreamStart<S>),
Invalid,
}
impl<S: AsyncWrite> ClientAuth<S> {
pub fn new(stream: XMPPStream<S>, creds: Credentials) -> Result<Self, String> {
let mechs: Vec<Box<Mechanism>> = vec![
Box::new(Scram::<Sha256>::from_credentials(creds.clone()).unwrap()),
Box::new(Scram::<Sha1>::from_credentials(creds.clone()).unwrap()),
Box::new(Plain::from_credentials(creds).unwrap()),
Box::new(Anonymous::new()),
];
let mech_names: Vec<String> =
match stream.stream_features.get_child("mechanisms", Some(NS_XMPP_SASL)) {
None =>
return Err("No auth mechanisms".to_owned()),
Some(mechs) =>
mechs.get_children("mechanism", Some(NS_XMPP_SASL))
.map(|mech_el| mech_el.content_str())
.collect(),
};
println!("SASL mechanisms offered: {:?}", mech_names);
for mut mech in mechs {
let name = mech.name().to_owned();
if mech_names.iter().any(|name1| *name1 == name) {
println!("SASL mechanism selected: {:?}", name);
let initial = try!(mech.initial());
let mut this = ClientAuth {
state: ClientAuthState::Invalid,
mechanism: mech,
};
this.send(
stream,
"auth", &[("mechanism".to_owned(), name)],
&initial
);
return Ok(this);
}
}
Err("No supported SASL mechanism available".to_owned())
}
fn send(&mut self, stream: XMPPStream<S>, nonza_name: &str, attrs: &[(String, String)], content: &[u8]) {
let mut nonza = xml::Element::new(
nonza_name.to_owned(),
Some(NS_XMPP_SASL.to_owned()),
attrs.iter()
.map(|&(ref name, ref value)| (name.clone(), None, value.clone()))
.collect()
);
nonza.text(content.to_base64(base64::URL_SAFE));
let send = stream.send(Packet::Stanza(nonza));
self.state = ClientAuthState::WaitSend(send);
}
}
impl<S: AsyncRead + AsyncWrite> Future for ClientAuth<S> {
type Item = XMPPStream<S>;
type Error = String;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let state = replace(&mut self.state, ClientAuthState::Invalid);
match state {
ClientAuthState::WaitSend(mut send) =>
match send.poll() {
Ok(Async::Ready(stream)) => {
self.state = ClientAuthState::WaitRecv(stream);
self.poll()
},
Ok(Async::NotReady) => {
self.state = ClientAuthState::WaitSend(send);
Ok(Async::NotReady)
},
Err(e) =>
Err(format!("{}", e)),
},
ClientAuthState::WaitRecv(mut stream) =>
match stream.poll() {
Ok(Async::Ready(Some(Packet::Stanza(ref stanza))))
if stanza.name == "challenge"
&& stanza.ns == Some(NS_XMPP_SASL.to_owned()) =>
{
let content = try!(
stanza.content_str()
.from_base64()
.map_err(|e| format!("{}", e))
);
let response = try!(self.mechanism.response(&content));
self.send(stream, "response", &[], &response);
self.poll()
},
Ok(Async::Ready(Some(Packet::Stanza(ref stanza))))
if stanza.name == "success"
&& stanza.ns == Some(NS_XMPP_SASL.to_owned()) =>
{
let start = stream.restart();
self.state = ClientAuthState::Start(start);
self.poll()
},
Ok(Async::Ready(Some(Packet::Stanza(ref stanza))))
if stanza.name == "failure"
&& stanza.ns == Some(NS_XMPP_SASL.to_owned()) =>
{
let mut e = None;
for child in &stanza.children {
match child {
&xml::Xml::ElementNode(ref child) => {
e = Some(child.name.clone());
break
},
_ => (),
}
}
let e = e.unwrap_or_else(|| "Authentication failure".to_owned());
Err(e)
},
Ok(Async::Ready(event)) => {
println!("ClientAuth ignore {:?}", event);
Ok(Async::NotReady)
},
Ok(_) => {
self.state = ClientAuthState::WaitRecv(stream);
Ok(Async::NotReady)
},
Err(e) =>
Err(format!("{}", e)),
},
ClientAuthState::Start(mut start) =>
match start.poll() {
Ok(Async::Ready(stream)) =>
Ok(Async::Ready(stream)),
Ok(Async::NotReady) => {
self.state = ClientAuthState::Start(start);
Ok(Async::NotReady)
},
Err(e) =>
Err(format!("{}", e)),
},
ClientAuthState::Invalid =>
unreachable!(),
}
}
}

135
src/client/bind.rs Normal file
View file

@ -0,0 +1,135 @@
use std::mem::replace;
use std::error::Error;
use std::str::FromStr;
use futures::*;
use futures::sink;
use tokio_io::{AsyncRead, AsyncWrite};
use xml;
use jid::Jid;
use xmpp_codec::*;
use xmpp_stream::*;
const NS_XMPP_BIND: &str = "urn:ietf:params:xml:ns:xmpp-bind";
const BIND_REQ_ID: &str = "resource-bind";
pub enum ClientBind<S: AsyncWrite> {
Unsupported(XMPPStream<S>),
WaitSend(sink::Send<XMPPStream<S>>),
WaitRecv(XMPPStream<S>),
Invalid,
}
impl<S: AsyncWrite> ClientBind<S> {
/// Consumes and returns the stream to express that you cannot use
/// the stream for anything else until the resource binding
/// req/resp are done.
pub fn new(stream: XMPPStream<S>) -> Self {
match stream.stream_features.get_child("bind", Some(NS_XMPP_BIND)) {
None =>
// No resource binding available,
// return the (probably // usable) stream immediately
ClientBind::Unsupported(stream),
Some(_) => {
let iq = make_bind_request(stream.jid.resource.as_ref());
let send = stream.send(Packet::Stanza(iq));
ClientBind::WaitSend(send)
},
}
}
}
fn make_bind_request(resource: Option<&String>) -> xml::Element {
let mut iq = xml::Element::new(
"iq".to_owned(),
None,
vec![("type".to_owned(), None, "set".to_owned()),
("id".to_owned(), None, BIND_REQ_ID.to_owned())]
);
{
let bind_el = iq.tag(
xml::Element::new(
"bind".to_owned(),
Some(NS_XMPP_BIND.to_owned()),
vec![]
));
resource.map(|resource| {
let resource_el = bind_el.tag(
xml::Element::new(
"resource".to_owned(),
Some(NS_XMPP_BIND.to_owned()),
vec![]
));
resource_el.text(resource.clone());
});
}
iq
}
impl<S: AsyncRead + AsyncWrite> Future for ClientBind<S> {
type Item = XMPPStream<S>;
type Error = String;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let state = replace(self, ClientBind::Invalid);
match state {
ClientBind::Unsupported(stream) =>
Ok(Async::Ready(stream)),
ClientBind::WaitSend(mut send) => {
match send.poll() {
Ok(Async::Ready(stream)) => {
replace(self, ClientBind::WaitRecv(stream));
self.poll()
},
Ok(Async::NotReady) => {
replace(self, ClientBind::WaitSend(send));
Ok(Async::NotReady)
},
Err(e) =>
Err(e.description().to_owned()),
}
},
ClientBind::WaitRecv(mut stream) => {
match stream.poll() {
Ok(Async::Ready(Some(Packet::Stanza(ref iq))))
if iq.name == "iq"
&& iq.get_attribute("id", None) == Some(BIND_REQ_ID) => {
match iq.get_attribute("type", None) {
Some("result") => {
get_bind_response_jid(&iq)
.map(|jid| stream.jid = jid);
Ok(Async::Ready(stream))
},
_ =>
Err("resource bind response".to_owned()),
}
},
Ok(Async::Ready(_)) => {
replace(self, ClientBind::WaitRecv(stream));
self.poll()
},
Ok(Async::NotReady) => {
replace(self, ClientBind::WaitRecv(stream));
Ok(Async::NotReady)
},
Err(e) =>
Err(e.description().to_owned()),
}
},
ClientBind::Invalid =>
unreachable!(),
}
}
}
fn get_bind_response_jid(iq: &xml::Element) -> Option<Jid> {
iq.get_child("bind", Some(NS_XMPP_BIND))
.and_then(|bind_el|
bind_el.get_child("jid", Some(NS_XMPP_BIND))
)
.and_then(|jid_el|
Jid::from_str(&jid_el.content_str())
.ok()
)
}

167
src/client/mod.rs Normal file
View file

@ -0,0 +1,167 @@
use std::mem::replace;
use std::str::FromStr;
use std::error::Error;
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpStream;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_tls::TlsStream;
use futures::*;
use jid::{Jid, JidParseError};
use xml;
use sasl::common::{Credentials, ChannelBinding};
use super::xmpp_codec::Packet;
use super::xmpp_stream;
use super::tcp::TcpClient;
use super::starttls::{NS_XMPP_TLS, StartTlsClient};
mod auth;
use self::auth::*;
mod bind;
use self::bind::*;
pub struct Client {
pub jid: Jid,
password: String,
state: ClientState,
}
type XMPPStream = xmpp_stream::XMPPStream<TlsStream<TcpStream>>;
enum ClientState {
Invalid,
Disconnected,
Connecting(Box<Future<Item=XMPPStream, Error=String>>),
Connected(XMPPStream),
// Sending,
// Drain,
}
impl Client {
pub fn new(jid: &str, password: &str, handle: &Handle) -> Result<Self, JidParseError> {
let jid = try!(Jid::from_str(jid));
let password = password.to_owned();
let connect = Self::make_connect(jid.clone(), password.clone(), handle);
Ok(Client {
jid, password,
state: ClientState::Connecting(connect),
})
}
fn make_connect(jid: Jid, password: String, handle: &Handle) -> Box<Future<Item=XMPPStream, Error=String>> {
use std::net::ToSocketAddrs;
let addr = "89.238.79.220:5222"
.to_socket_addrs().unwrap()
.next().unwrap();
let username = jid.node.as_ref().unwrap().to_owned();
let password = password;
Box::new(
TcpClient::connect(
jid,
&addr,
handle
).map_err(|e| format!("{}", e)
).and_then(|stream| {
if Self::can_starttls(&stream) {
Self::starttls(stream)
} else {
panic!("No STARTTLS")
}
}).and_then(move |stream| {
Self::auth(stream, username, password).expect("auth")
}).and_then(|stream| {
Self::bind(stream)
}).and_then(|stream| {
println!("Bound to {}", stream.jid);
let presence = xml::Element::new("presence".to_owned(), None, vec![]);
stream.send(Packet::Stanza(presence))
.map_err(|e| format!("{}", e))
})
)
}
fn can_starttls<S>(stream: &xmpp_stream::XMPPStream<S>) -> bool {
stream.stream_features
.get_child("starttls", Some(NS_XMPP_TLS))
.is_some()
}
fn starttls<S: AsyncRead + AsyncWrite>(stream: xmpp_stream::XMPPStream<S>) -> StartTlsClient<S> {
StartTlsClient::from_stream(stream)
}
fn auth<S: AsyncRead + AsyncWrite>(stream: xmpp_stream::XMPPStream<S>, username: String, password: String) -> Result<ClientAuth<S>, String> {
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)
}
}
#[derive(Debug)]
pub enum ClientEvent {
Online,
Disconnected,
Stanza(xml::Element),
}
impl Stream for Client {
type Item = ClientEvent;
type Error = String;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
println!("stream.poll");
let state = replace(&mut self.state, ClientState::Invalid);
match state {
ClientState::Invalid =>
Err("invalid client state".to_owned()),
ClientState::Disconnected =>
Ok(Async::NotReady),
ClientState::Connecting(mut connect) => {
match connect.poll() {
Ok(Async::Ready(stream)) => {
println!("connected");
self.state = ClientState::Connected(stream);
self.poll()
},
Ok(Async::NotReady) => {
self.state = ClientState::Connecting(connect);
Ok(Async::NotReady)
},
Err(e) =>
Err(e),
}
},
ClientState::Connected(mut stream) => {
match stream.poll() {
Ok(Async::NotReady) => {
self.state = ClientState::Connected(stream);
Ok(Async::NotReady)
},
Ok(Async::Ready(None)) => {
// EOF
self.state = ClientState::Disconnected;
Ok(Async::Ready(Some(ClientEvent::Disconnected)))
},
Ok(Async::Ready(Some(Packet::Stanza(stanza)))) => {
self.state = ClientState::Connected(stream);
Ok(Async::Ready(Some(ClientEvent::Stanza(stanza))))
},
Ok(Async::Ready(_)) => {
self.state = ClientState::Connected(stream);
Ok(Async::NotReady)
},
Err(e) =>
Err(e.description().to_owned()),
}
},
}
}
}