1//! Components in XMPP are services/gateways that are logged into an
2//! XMPP server under a JID consisting of just a domain name. They are
3//! allowed to use any user and resource identifiers in their stanzas.
4use std::mem::replace;
5use std::str::FromStr;
6use tokio::net::TcpStream;
7use tokio_io::{AsyncRead, AsyncWrite};
8use futures::{Future, Stream, Poll, Async, Sink, StartSend, AsyncSink, done};
9use minidom::Element;
10use jid::{Jid, JidParseError};
11
12use super::xmpp_codec::Packet;
13use super::xmpp_stream;
14use super::happy_eyeballs::Connecter;
15use super::event::Event;
16use super::Error;
17
18mod auth;
19use self::auth::ComponentAuth;
20
21/// Component connection to an XMPP server
22pub struct Component {
23 /// The component's Jabber-Id
24 pub jid: Jid,
25 state: ComponentState,
26}
27
28type XMPPStream = xmpp_stream::XMPPStream<TcpStream>;
29const NS_JABBER_COMPONENT_ACCEPT: &str = "jabber:component:accept";
30
31enum ComponentState {
32 Invalid,
33 Disconnected,
34 Connecting(Box<Future<Item=XMPPStream, Error=Error>>),
35 Connected(XMPPStream),
36}
37
38impl Component {
39 /// Start a new XMPP component
40 ///
41 /// Start polling the returned instance so that it will connect
42 /// and yield events.
43 pub fn new(jid: &str, password: &str, server: &str, port: u16) -> Result<Self, JidParseError> {
44 let jid = Jid::from_str(jid)?;
45 let password = password.to_owned();
46 let connect = Self::make_connect(jid.clone(), password, server, port);
47 Ok(Component {
48 jid,
49 state: ComponentState::Connecting(Box::new(connect)),
50 })
51 }
52
53 fn make_connect(jid: Jid, password: String, server: &str, port: u16) -> impl Future<Item=XMPPStream, Error=Error> {
54 let jid1 = jid.clone();
55 let password = password;
56 done(Connecter::from_lookup(server, None, port))
57 .flatten()
58 .and_then(move |tcp_stream| {
59 xmpp_stream::XMPPStream::start(tcp_stream, jid1, NS_JABBER_COMPONENT_ACCEPT.to_owned())
60 }).and_then(move |xmpp_stream| {
61 Self::auth(xmpp_stream, password).expect("auth")
62 })
63 }
64
65 fn auth<S: AsyncRead + AsyncWrite>(stream: xmpp_stream::XMPPStream<S>, password: String) -> Result<ComponentAuth<S>, Error> {
66 ComponentAuth::new(stream, password)
67 }
68}
69
70impl Stream for Component {
71 type Item = Event;
72 type Error = Error;
73
74 fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
75 let state = replace(&mut self.state, ComponentState::Invalid);
76
77 match state {
78 ComponentState::Invalid =>
79 Err(Error::InvalidState),
80 ComponentState::Disconnected =>
81 Ok(Async::Ready(None)),
82 ComponentState::Connecting(mut connect) => {
83 match connect.poll() {
84 Ok(Async::Ready(stream)) => {
85 self.state = ComponentState::Connected(stream);
86 Ok(Async::Ready(Some(Event::Online)))
87 },
88 Ok(Async::NotReady) => {
89 self.state = ComponentState::Connecting(connect);
90 Ok(Async::NotReady)
91 },
92 Err(e) =>
93 Err(e),
94 }
95 },
96 ComponentState::Connected(mut stream) => {
97 // Poll sink
98 match stream.poll_complete() {
99 Ok(Async::NotReady) => (),
100 Ok(Async::Ready(())) => (),
101 Err(e) =>
102 return Err(e)?,
103 };
104
105 // Poll stream
106 match stream.poll() {
107 Ok(Async::NotReady) => {
108 self.state = ComponentState::Connected(stream);
109 Ok(Async::NotReady)
110 },
111 Ok(Async::Ready(None)) => {
112 // EOF
113 self.state = ComponentState::Disconnected;
114 Ok(Async::Ready(Some(Event::Disconnected)))
115 },
116 Ok(Async::Ready(Some(Packet::Stanza(stanza)))) => {
117 self.state = ComponentState::Connected(stream);
118 Ok(Async::Ready(Some(Event::Stanza(stanza))))
119 },
120 Ok(Async::Ready(_)) => {
121 self.state = ComponentState::Connected(stream);
122 Ok(Async::NotReady)
123 },
124 Err(e) =>
125 Err(e)?,
126 }
127 },
128 }
129 }
130}
131
132impl Sink for Component {
133 type SinkItem = Element;
134 type SinkError = Error;
135
136 fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
137 match self.state {
138 ComponentState::Connected(ref mut stream) =>
139 match stream.start_send(Packet::Stanza(item)) {
140 Ok(AsyncSink::NotReady(Packet::Stanza(stanza))) =>
141 Ok(AsyncSink::NotReady(stanza)),
142 Ok(AsyncSink::NotReady(_)) =>
143 panic!("Component.start_send with stanza but got something else back"),
144 Ok(AsyncSink::Ready) => {
145 Ok(AsyncSink::Ready)
146 },
147 Err(e) =>
148 Err(e)?,
149 },
150 _ =>
151 Ok(AsyncSink::NotReady(item)),
152 }
153 }
154
155 fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
156 match &mut self.state {
157 &mut ComponentState::Connected(ref mut stream) =>
158 stream.poll_complete()
159 .map_err(|e| e.into()),
160 _ =>
161 Ok(Async::Ready(())),
162 }
163 }
164}