summaryrefslogtreecommitdiffstats
path: root/src/client/encrypted.rs
blob: e8b72715b1a0eb81a78d59470813a4ae62f5291a (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
use std::str;

use quick_xml::{
    events::{BytesDecl, Event},
    name::QName,
    Reader, Writer,
};
use rsasl::prelude::{Mechname, SASLClient};
use tokio::io::{BufReader, ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio_native_tls::TlsStream;

use crate::stanza::{
    sasl::{Auth, Response},
    stream::{Stream, StreamFeature},
};
use crate::stanza::{
    sasl::{Challenge, Success},
    Element,
};
use crate::Jabber;
use crate::Result;

pub struct JabberClient<'j> {
    reader: Reader<BufReader<ReadHalf<TlsStream<TcpStream>>>>,
    writer: Writer<WriteHalf<TlsStream<TcpStream>>>,
    jabber: &'j mut Jabber<'j>,
}

impl<'j> JabberClient<'j> {
    pub fn new(
        reader: Reader<BufReader<ReadHalf<TlsStream<TcpStream>>>>,
        writer: Writer<WriteHalf<TlsStream<TcpStream>>>,
        jabber: &'j mut Jabber<'j>,
    ) -> Self {
        Self {
            reader,
            writer,
            jabber,
        }
    }

    pub async fn start_stream(&mut self) -> Result<()> {
        // client to server
        let declaration = BytesDecl::new("1.0", None, None);
        let server = &self.jabber.server.to_owned().try_into()?;
        let stream_element =
            Stream::new_client(&self.jabber.jid, server, None, Some("en".to_string()));
        self.writer
            .write_event_async(Event::Decl(declaration))
            .await;
        let stream_element: Element<'_> = stream_element.into();
        stream_element.write_start(&mut self.writer).await?;
        // server to client
        let mut buf = Vec::new();
        self.reader.read_event_into_async(&mut buf).await?;
        let _stream_response = Element::read_start(&mut self.reader).await?;
        Ok(())
    }

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

    pub async fn negotiate(&mut self) -> Result<()> {
        loop {
            println!("loop");
            let features = self.get_features().await?;
            println!("features: {:?}", features);
            match &features[0] {
                StreamFeature::Sasl(sasl) => {
                    println!("sasl?");
                    self.sasl(&sasl).await?;
                }
                StreamFeature::Bind => todo!(),
                x => println!("{:?}", x),
            }
        }
    }

    pub async fn sasl(&mut self, mechanisms: &Vec<String>) -> Result<()> {
        println!("{:?}", mechanisms);
        let sasl = SASLClient::new(self.jabber.auth.clone());
        let mut offered_mechs: Vec<&Mechname> = Vec::new();
        for mechanism in mechanisms {
            offered_mechs.push(Mechname::parse(mechanism.as_bytes())?)
        }
        println!("{:?}", offered_mechs);
        let mut session = sasl.start_suggested(&offered_mechs)?;
        let selected_mechanism = session.get_mechname().as_str().to_owned();
        println!("selected mech: {:?}", selected_mechanism);
        let mut data: Option<Vec<u8>> = None;
        if !session.are_we_first() {
            // if not first mention the mechanism then get challenge data
            // mention mechanism
            let auth = Auth {
                mechanism: selected_mechanism.as_str(),
                sasl_data: "=",
            };
            Into::<Element>::into(auth).write(&mut self.writer).await?;
            // get challenge data
            let challenge = &Element::read(&mut self.reader).await?;
            let challenge: Challenge = challenge.try_into()?;
            println!("challenge: {:?}", challenge);
            data = Some(challenge.sasl_data.to_owned());
            println!("we didn't go first");
        } else {
            // if first, mention mechanism and send data
            let mut sasl_data = Vec::new();
            session.step64(None, &mut sasl_data).unwrap();
            let auth = Auth {
                mechanism: selected_mechanism.as_str(),
                sasl_data: str::from_utf8(&sasl_data)?,
            };
            println!("{:?}", auth);
            Into::<Element>::into(auth).write(&mut self.writer).await?;

            let server_response = Element::read(&mut self.reader).await?;
            println!("server_response: {:#?}", server_response);
            match TryInto::<Challenge>::try_into(&server_response) {
                Ok(challenge) => data = Some(challenge.sasl_data.to_owned()),
                Err(_) => {
                    let success = TryInto::<Success>::try_into(&server_response)?;
                    if let Some(sasl_data) = success.sasl_data {
                        data = Some(sasl_data.to_owned())
                    }
                }
            }
            println!("we went first");
        }

        // stepping the authentication exchange to completion
        if data != None {
            println!("data: {:?}", data);
            let mut sasl_data = Vec::new();
            while {
                // decide if need to send more data over
                let state = session
                    .step64(data.as_deref(), &mut sasl_data)
                    .expect("step errored!");
                state.is_running()
            } {
                // While we aren't finished, receive more data from the other party
                let response = Response {
                    sasl_data: str::from_utf8(&sasl_data)?,
                };
                println!("response: {:?}", response);
                Into::<Element>::into(response)
                    .write(&mut self.writer)
                    .await?;

                let server_response = Element::read(&mut self.reader).await?;
                println!("server_response: {:?}", server_response);
                match TryInto::<Challenge>::try_into(&server_response) {
                    Ok(challenge) => data = Some(challenge.sasl_data.to_owned()),
                    Err(_) => {
                        let success = TryInto::<Success>::try_into(&server_response)?;
                        if let Some(sasl_data) = success.sasl_data {
                            data = Some(sasl_data.to_owned())
                        }
                    }
                }
            }
        }
        self.start_stream().await?;
        Ok(())
    }
}