summaryrefslogtreecommitdiffstats
path: root/src/jabber.rs
blob: 3583d19d678df4061988634b976d4fcee67653fb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use std::sync::Arc;

use quick_xml::{events::Event, se::Serializer, NsReader, Writer};
use rsasl::prelude::SASLConfig;
use serde::Serialize;
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, ReadHalf, WriteHalf};

use crate::connection::{Tls, Unencrypted};
use crate::error::JabberError;
use crate::stanza::stream::Stream;
use crate::stanza::DECLARATION;
use crate::Result;
use crate::JID;

pub struct Jabber<S>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    reader: NsReader<BufReader<ReadHalf<S>>>,
    writer: Writer<WriteHalf<S>>,
    jid: Option<JID>,
    auth: Option<Arc<SASLConfig>>,
    server: String,
}

impl<S> Jabber<S>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    pub fn new(
        reader: ReadHalf<S>,
        writer: WriteHalf<S>,
        jid: Option<JID>,
        auth: Option<Arc<SASLConfig>>,
        server: String,
    ) -> Self {
        let reader = NsReader::from_reader(BufReader::new(reader));
        let writer = Writer::new(writer);
        Self {
            reader,
            writer,
            jid,
            auth,
            server,
        }
    }
}

impl<S> Jabber<S>
where
    S: AsyncRead + AsyncWrite + Unpin,
    Writer<tokio::io::WriteHalf<S>>: AsyncWriteExt,
    Writer<tokio::io::WriteHalf<S>>: AsyncWrite,
{
    pub async fn start_stream(&mut self) -> Result<()> {
        // client to server

        // declaration
        self.writer.write_event_async(DECLARATION.clone()).await?;

        // opening stream element
        let server = &self.server.to_owned().try_into()?;
        let stream_element = Stream::new_client(None, server, None, "en");
        // TODO: nicer function to serialize to xml writer
        let mut buffer = String::new();
        let ser = Serializer::new(&mut buffer);
        stream_element.serialize(ser).unwrap();
        self.writer.write_all(buffer.as_bytes());

        // server to client

        // may or may not send a declaration
        let mut buf = Vec::new();
        let mut first_event = self.reader.read_resolved_event_into_async(&mut buf).await?;
        match first_event {
            (quick_xml::name::ResolveResult::Unbound, Event::Decl(e)) => {
                if let Ok(version) = e.version() {
                    if version.as_ref() == b"1.0" {
                        first_event = self.reader.read_resolved_event_into_async(&mut buf).await?
                    } else {
                        // todo: error
                        todo!()
                    }
                } else {
                    first_event = self.reader.read_resolved_event_into_async(&mut buf).await?
                }
            }
            _ => (),
        }

        // receive stream element and validate
        let stream_response: Stream;
        match first_event {
            (quick_xml::name::ResolveResult::Bound(ns), Event::Start(e)) => {
                if ns.0 == crate::stanza::stream::XMLNS.as_bytes() {
                    // stream_response = Stream::new(
                    //     e.try_get_attribute("from")?.try_map(|attribute| {
                    //         str::from_utf8(attribute.value.as_ref())?
                    //             .try_into()?
                    //             .as_ref()
                    //     })?,
                    //     e.try_get_attribute("to")?.try_map(|attribute| {
                    //         str::from_utf8(attribute.value.as_ref())?
                    //             .try_into()?
                    //             .as_ref()
                    //     })?,
                    //     e.try_get_attribute("id")?.try_map(|attribute| {
                    //         str::from_utf8(attribute.value.as_ref())?
                    //             .try_into()?
                    //             .as_ref()
                    //     })?,
                    //     e.try_get_attribute("version")?.try_map(|attribute| {
                    //         str::from_utf8(attribute.value.as_ref())?
                    //             .try_into()?
                    //             .as_ref()
                    //     })?,
                    //     e.try_get_attribute("lang")?.try_map(|attribute| {
                    //         str::from_utf8(attribute.value.as_ref())?
                    //             .try_into()?
                    //             .as_ref()
                    //     })?,
                    // );
                    return Ok(());
                } else {
                    return Err(JabberError::BadStream);
                }
            }
            // TODO: errors for incorrect namespace
            (quick_xml::name::ResolveResult::Unbound, Event::Decl(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::Start(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::End(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::Empty(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::Text(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::CData(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::Comment(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::Decl(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::PI(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::DocType(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unknown(_), Event::Eof) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::Start(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::End(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::Empty(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::Text(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::CData(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::Comment(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::PI(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::DocType(_)) => todo!(),
            (quick_xml::name::ResolveResult::Unbound, Event::Eof) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::End(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::Empty(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::Text(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::CData(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::Comment(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::Decl(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::PI(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::DocType(_)) => todo!(),
            (quick_xml::name::ResolveResult::Bound(_), Event::Eof) => todo!(),
        }
    }
}

// pub async fn get_features(&mut self) -> Result<Vec<StreamFeature>> {
//     Element::read(&mut self.reader).await?.try_into()
// }

impl Jabber<Unencrypted> {
    pub async fn starttls(mut self) -> Result<Jabber<Tls>> {
        todo!()
    }
    //     let mut starttls_element = BytesStart::new("starttls");
    //     starttls_element.push_attribute(("xmlns", "urn:ietf:params:xml:ns:xmpp-tls"));
    //     self.writer
    //         .write_event_async(Event::Empty(starttls_element))
    //         .await
    //         .unwrap();
    //     let mut buf = Vec::new();
    //     match self.reader.read_event_into_async(&mut buf).await.unwrap() {
    //         Event::Empty(e) => match e.name() {
    //             QName(b"proceed") => {
    //                 let connector = TlsConnector::new().unwrap();
    //                 let stream = self
    //                     .reader
    //                     .into_inner()
    //                     .into_inner()
    //                     .unsplit(self.writer.into_inner());
    //                 if let Ok(tlsstream) = tokio_native_tls::TlsConnector::from(connector)
    //                     .connect(&self.jabber.server, stream)
    //                     .await
    //                 {
    //                     let (read, write) = tokio::io::split(tlsstream);
    //                     let reader = Reader::from_reader(BufReader::new(read));
    //                     let writer = Writer::new(write);
    //                     let mut client =
    //                         super::encrypted::JabberClient::new(reader, writer, self.jabber);
    //                     client.start_stream().await?;
    //                     return Ok(client);
    //                 }
    //             }
    //             QName(_) => return Err(JabberError::TlsNegotiation),
    //         },
    //         _ => return Err(JabberError::TlsNegotiation),
    //     }
    //     Err(JabberError::TlsNegotiation)
    // }
}