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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// standard
use std::clone::Clone;
use std::convert::TryInto;
use std::net::TcpStream;

// extern crates
use bson::doc;
use bson::spec::BinarySubtype;
use bson::{Binary, Bson};
use honk_rpc::honk_rpc::{RequestCookie, Response, Session};
use rand::rngs::OsRng;
use rand::RngCore;
use tor_interface::tor_crypto::*;

// internal crates
use crate::ascii_string::*;
use crate::gosling::*;

//
// Endpoint Client
//

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("HonkRPC method failed: {0}")]
    HonkRPCFailure(#[from] honk_rpc::honk_rpc::Error),

    #[error("client received unexpected response: {0}")]
    UnexpectedResponseReceived(String),

    #[error("client is in invalid state: {0}")]
    InvalidState(String),

    #[error("incorrect usage: {0}")]
    IncorrectUsage(String),
}

pub(crate) enum EndpointClientEvent {
    HandshakeCompleted { stream: TcpStream },
}

#[derive(Debug, PartialEq)]
enum EndpointClientState {
    BeginHandshake,
    WaitingForServerCookie,
    WaitingForProofVerification,
    HandshakeComplete,
}

pub(crate) struct EndpointClient {
    // session data
    rpc: Option<Session<TcpStream>>,
    pub server_service_id: V3OnionServiceId,
    pub requested_channel: AsciiString,
    client_service_id: V3OnionServiceId,
    client_ed25519_private: Ed25519PrivateKey,

    // state machine data
    state: EndpointClientState,
    begin_handshake_request_cookie: Option<RequestCookie>,
    send_response_request_cookie: Option<RequestCookie>,
}

impl EndpointClient {
    fn get_state(&self) -> String {
        format!("{{ state: {:?}, begin_handshake_request_cookie: {:?}, send_response_request_cookie: {:?} }}", self.state, self.begin_handshake_request_cookie, self.send_response_request_cookie)
    }

    pub fn new(
        rpc: Session<TcpStream>,
        server_service_id: V3OnionServiceId,
        requested_channel: AsciiString,
        client_ed25519_private: Ed25519PrivateKey,
    ) -> Self {
        Self {
            rpc: Some(rpc),
            server_service_id,
            requested_channel,
            client_service_id: V3OnionServiceId::from_private_key(&client_ed25519_private),
            client_ed25519_private,

            state: EndpointClientState::BeginHandshake,
            begin_handshake_request_cookie: None,
            send_response_request_cookie: None,
        }
    }

    pub fn update(&mut self) -> Result<Option<EndpointClientEvent>, Error> {
        if self.state == EndpointClientState::HandshakeComplete {
            return Err(Error::IncorrectUsage("update() may not be called after HandshakeComplete has been returned from previous update() call".to_string()));
        }

        // update our rpc session
        if let Some(rpc) = self.rpc.as_mut() {
            rpc.update(None)?;

            // client state machine
            match (
                &self.state,
                self.begin_handshake_request_cookie,
                self.send_response_request_cookie,
            ) {
                (&EndpointClientState::BeginHandshake, None, None) => {
                    self.begin_handshake_request_cookie = Some(rpc.client_call(
                        "gosling_endpoint",
                        "begin_handshake",
                        0,
                        doc! {
                            "version" : bson::Bson::String(GOSLING_PROTOCOL_VERSION.to_string()),
                            "client_identity" : bson::Bson::String(self.client_service_id.to_string()),
                            "channel" : bson::Bson::String(self.requested_channel.to_string()),
                        },
                    ).unwrap());
                    self.state = EndpointClientState::WaitingForServerCookie;
                    Ok(None)
                }
                (
                    &EndpointClientState::WaitingForServerCookie,
                    Some(begin_handshake_request_cookie),
                    None, // send_response_request_cookie
                ) => {
                    if let Some(response) = rpc.client_next_response() {
                        let result = match response {
                            Response::Pending { cookie } => {
                                if cookie == begin_handshake_request_cookie {
                                    return Ok(None);
                                } else {
                                    return Err(Error::UnexpectedResponseReceived(
                                        "received unexpected pending response".to_string(),
                                    ));
                                }
                            }
                            Response::Error { cookie, error_code } => {
                                if cookie != begin_handshake_request_cookie {
                                    return Err(Error::UnexpectedResponseReceived(format!(
                                        "received unexpected error response; rpc error_code: {}",
                                        error_code
                                    )));
                                }
                                return Err(Error::UnexpectedResponseReceived(format!(
                                    "received unexpected rpc error_code: {}",
                                    error_code
                                )));
                            }
                            Response::Success { cookie, result } => {
                                if cookie == begin_handshake_request_cookie {
                                    result
                                } else {
                                    return Err(Error::UnexpectedResponseReceived(
                                        "received unexpected success response".to_string(),
                                    ));
                                }
                            }
                        };

                        if let Some(bson::Bson::Document(result)) = result {
                            if let Some(Bson::Binary(Binary {
                                subtype: BinarySubtype::Generic,
                                bytes: server_cookie,
                            })) = result.get("server_cookie")
                            {
                                // build arguments for send_response()

                                // client_cookie
                                let mut client_cookie: ClientCookie = Default::default();
                                OsRng.fill_bytes(&mut client_cookie);

                                // client_identity_proof_signature
                                let server_cookie: ServerCookie =
                                    match server_cookie.clone().try_into() {
                                        Ok(server_cookie) => server_cookie,
                                        Err(_) => {
                                            return Err(Error::UnexpectedResponseReceived(format!(
                                                "unable to convert '{:?}' to server cookie",
                                                server_cookie
                                            )))
                                        }
                                    };
                                let client_identity_proof = build_client_proof(
                                    DomainSeparator::GoslingEndpoint,
                                    &self.requested_channel,
                                    &self.client_service_id,
                                    &self.server_service_id,
                                    &client_cookie,
                                    &server_cookie,
                                );
                                let client_identity_proof_signature = self
                                    .client_ed25519_private
                                    .sign_message(&client_identity_proof);

                                // build our args object for rpc call
                                let args = doc! {
                                    "client_cookie" : Bson::Binary(bson::Binary{subtype: BinarySubtype::Generic, bytes: client_cookie.to_vec()}),
                                    "client_identity_proof_signature" : Bson::Binary(bson::Binary{subtype: BinarySubtype::Generic, bytes: client_identity_proof_signature.to_bytes().to_vec()}),
                                };

                                // make rpc call
                                self.send_response_request_cookie = Some(
                                    rpc.client_call("gosling_endpoint", "send_response", 0, args)
                                        .unwrap(),
                                );

                                self.state = EndpointClientState::WaitingForProofVerification;
                            } else {
                                return Err(Error::UnexpectedResponseReceived(format!(
                                    "begin_handshake() returned unexpected value: {}",
                                    result
                                )));
                            }
                        } else {
                            return Err(Error::UnexpectedResponseReceived(format!(
                                "begin_handshake() returned unexpected value: {:?}",
                                result
                            )));
                        }
                    }
                    Ok(None)
                }
                (
                    &EndpointClientState::WaitingForProofVerification,
                    Some(_begin_handshake_request_cookie),
                    Some(send_response_request_cookie),
                ) => {
                    if let Some(response) = rpc.client_next_response() {
                        let result = match response {
                            Response::Pending { cookie } => {
                                if cookie == send_response_request_cookie {
                                    return Ok(None);
                                } else {
                                    return Err(Error::UnexpectedResponseReceived(
                                        "received unexpected pending response".to_string(),
                                    ));
                                }
                            }
                            Response::Error { cookie, error_code } => {
                                if cookie == send_response_request_cookie {
                                    return Err(Error::UnexpectedResponseReceived(format!(
                                        "received unexpected error response; rpc error_code: {}",
                                        error_code
                                    )));
                                }
                                return Err(Error::UnexpectedResponseReceived(format!(
                                    "received unexpected rpc error_code: {}",
                                    error_code
                                )));
                            }
                            Response::Success { cookie, result } => {
                                if cookie == send_response_request_cookie {
                                    result
                                } else {
                                    return Err(Error::UnexpectedResponseReceived(
                                        "received unexpected success response".to_string(),
                                    ));
                                }
                            }
                        };

                        if let Some(Bson::Document(result)) = result {
                            if result.is_empty() {
                                self.state = EndpointClientState::HandshakeComplete;
                                let stream = std::mem::take(&mut self.rpc).unwrap().into_stream();
                                return Ok(Some(EndpointClientEvent::HandshakeCompleted {
                                    stream,
                                }));
                            } else {
                                return Err(Error::UnexpectedResponseReceived(format!(
                                    "received unexpected data from send_response(): {:?}",
                                    result
                                )));
                            }
                        } else {
                            return Err(Error::UnexpectedResponseReceived(format!(
                                "received unexpected data from send_response(): {:?}",
                                result
                            )));
                        }
                    }
                    Ok(None)
                }
                _ => Err(Error::InvalidState(self.get_state())),
            }
        } else {
            Err(Error::InvalidState(self.get_state()))
        }
    }
}