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
use failure::Error;
use crate::connection::*;
use super::transport::Transport;
use std::net::SocketAddr;
use std::collections::HashMap;
use crate::packets::RawPacket;

mod configuration;
pub use configuration::Configuration;

mod event;
pub use event::Event;

mod error;
pub use error::ClientError;

use crate::security::{Secret, ConnectionToken};
use crate::packets::{OutgoingPacket, PacketType};

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub enum ConnectionState {
    Disconnected,
    Connecting,
    Connected,
}

pub struct Client {
    configuration: Configuration,
    transport: Box<dyn Transport>,
    connections: ConnectionList,
    states: ConnectionDataList<ConnectionState>,
    addresses: ConnectionDataList<SocketAddr>,
    timeouts: ConnectionDataList<usize>,
    heartbeats: ConnectionDataList<usize>,
    sequence_numbers: ConnectionDataList<u64>,
    secrets: ConnectionDataList<Secret>,
    connection_tokens: ConnectionDataList<ConnectionToken>,
    address_to_connection: HashMap<SocketAddr, Connection>,
}

impl Client {
    pub fn new(configuration: Configuration, transport: Box<dyn Transport>) -> Self {
        let max_connections = configuration.max_connections;

        Self {
            configuration,
            transport,
            connections: ConnectionList::new(max_connections),
            states: ConnectionDataList::new(max_connections),
            addresses: ConnectionDataList::new(max_connections),
            timeouts: ConnectionDataList::new(max_connections),
            heartbeats: ConnectionDataList::new(max_connections),
            sequence_numbers: ConnectionDataList::new(max_connections),
            secrets: ConnectionDataList::new(max_connections),
            connection_tokens: ConnectionDataList::new(max_connections),
            address_to_connection: HashMap::new(),
        }
    }

    pub fn connect(&mut self, remote_address: SocketAddr, secret: Secret, connection_token: ConnectionToken) -> Result<Connection, Error> {

        if self.address_to_connection.contains_key(&remote_address) {
            return Err(ClientError::AlreadyConnectedToAddress{ address: remote_address }.into());
        }

        if let Some(connection) = self.connections.create_connection() {

            self.addresses.set(connection, remote_address);
            self.address_to_connection.insert(remote_address, connection);
            self.timeouts.set(connection, self.configuration.timeout);
            self.heartbeats.set(connection, self.configuration.heartbeat);
            self.sequence_numbers.set(connection, 0);
            self.states.set(connection, ConnectionState::Connecting);
            self.secrets.set(connection, secret);
            self.connection_tokens.set(connection, connection_token);

            self.send_connection_message(connection)?;

            Ok(connection)

        } else {
            Err(ClientError::MaximumConnectionsReached.into())
        }
    }

    pub fn update(&mut self) -> Vec<Event> {
        let mut poll_again = true;
        let mut events = Vec::new();
        
        while poll_again {
            let mut buffer = [0; 1500];
            match self.transport.poll(&mut buffer) {
                Ok(Some((length, address))) => {
                    let packet = RawPacket::new(buffer, length);

                    if let Some(connection) = self.find_connection(&address) {
                        self.handle_message(connection, packet, &mut events);
                    } else {
                        println!("message from unknown source");
                    }
                },
                Ok(None) => {
                    poll_again = false;
                },
                Err(error) => {
                    println!("{}", error);
                },
            }
        }

        let connections: Vec<Connection> = self.connections.into_iter().collect();
        for connection in connections {
            
            // manage timeouts
            let timeout = self.timeouts.get(connection).expect("No timeout set for connection") - 1;
            if timeout == 0 {
                let address = self.addresses.get(connection).unwrap();
                
                self.address_to_connection.remove(address);
                self.states.set(connection, ConnectionState::Disconnected);
                self.addresses.remove(connection);
                self.timeouts.remove(connection);
                self.heartbeats.remove(connection);
                self.sequence_numbers.remove(connection);
                self.secrets.remove(connection);
                self.connection_tokens.remove(connection);

                self.connections.delete_connection(connection).unwrap();
                events.push(Event::Disconnected { connection });
                continue;

            } else {
                self.timeouts.set(connection, timeout);
            }

            // manage heartbeats
            let heartbeat = self.heartbeats.get(connection).expect("No heartbeat set for connection") - 1;
            if heartbeat == 0 {

                let state = self.get_connection_state(connection);
                match state {
                    Some(ConnectionState::Connected) => {
                        self.send_heartbeat_message(connection).expect("Could not send heartbeat message");
                    },
                    Some(ConnectionState::Connecting) => {
                        self.send_connection_message(connection).expect("Could not send connection message");
                    },
                    _ => {
                        panic!("this should not happen");
                    }
                }
            } else {
                self.heartbeats.set(connection, heartbeat);
            }
        }

        events
    }

    pub fn send(&mut self, packet: OutgoingPacket, connection: Connection) -> Result<(), Error> {
        match self.get_connection_state(connection) {
            Some(ConnectionState::Connected) => {
                Ok(self.send_internal(packet, connection, PacketType::Payload)?)
            },
            Some(ConnectionState::Connecting) => {
                Err(ClientError::ConnectionStillConnecting.into())
            },
            Some(ConnectionState::Disconnected) => {
                Err(ClientError::ConnectionDisconnected.into())
            },
            None => {
                Err(ClientError::ConnectionNotFound.into())
            },
        }
    }

    fn send_internal(&mut self, packet: OutgoingPacket, connection: Connection, packet_type: PacketType) -> Result<(), Error> {
        let sequence_number = self.sequence_numbers.get(connection).expect("No sequence number for connection found") + 1;
        self.sequence_numbers.set(connection, sequence_number);
        let secret = self.secrets.get(connection).expect("No secret for connection found");

        let raw = packet.write_header_and_sign(sequence_number, 0, [0x0, 0x0, 0x0, 0x0], packet_type.to_u8(), secret);
        let address = self.addresses.get(connection).expect("No address for connection found");

        // TODO check bytes sent?
        let _bytes_sent = self.transport.send(address, raw.get_buffer())?;

        self.heartbeats.set(connection, self.configuration.heartbeat);

        Ok(())
    }

    fn find_connection(&self, address: &SocketAddr) -> Option<Connection> {
        match self.address_to_connection.get(&address) {
            Some(c) => Some(*c),
            None => None,
        }
    }

    fn get_connection_state(&self, connection: Connection) -> Option<ConnectionState> {
        match self.states.get(connection) {
            Some(c) => Some(*c),
            None => None,
        }
    }

    fn handle_message(&mut self, connection: Connection, packet: RawPacket, events: &mut Vec<Event>) {
        let secret = self.secrets.get(connection).expect("Secret for connection not found");

        if let Some(incoming) = packet.verify(secret) {
            let state = self.states.get(connection).expect("State for connection not found").clone();

            if state == ConnectionState::Connecting {
                self.states.set(connection, ConnectionState::Connected);
                self.timeouts.set(connection, self.configuration.timeout);
                self.heartbeats.set(connection, self.configuration.heartbeat);
                self.connection_tokens.remove(connection);

                events.push(Event::Connected { connection });

                if incoming.get_packet_type() == Some(PacketType::Payload) {
                    events.push(Event::Message {
                        connection,
                        payload: incoming.into_payload(),
                    });
                }
            } else {

                match incoming.get_packet_type() {
                    Some(PacketType::Payload) => {
                        self.timeouts.set(connection, self.configuration.timeout);

                        events.push(Event::Message {
                            connection,
                            payload: incoming.into_payload(),
                        });
                    },
                    Some(PacketType::Heartbeat) => {
                        self.timeouts.set(connection, self.configuration.timeout);
                    },
                    Some(packet_type) => {
                        println!("got unexpected packet type {:?}", packet_type);
                    }
                    _ => {
                        println!("got invalid packet type");
                    }
                }
            }
        } else {
            println!("got invalid packet");
        }
    }

    fn send_connection_message(&mut self, connection: Connection) -> Result<(), Error> {
        use std::io::Write;
        
        let connection_token = self.connection_tokens.get(connection).expect("No connection token for connection");

        let mut packet = OutgoingPacket::new();
        packet.write(connection_token.get_bytes())?;
        
        self.send_internal(packet, connection, PacketType::Connection)?;

        Ok(())
    }

    fn send_heartbeat_message(&mut self, connection: Connection) -> Result<(), Error> {
        let packet = OutgoingPacket::new();
        self.send_internal(packet, connection, PacketType::Heartbeat)?;

        Ok(())
    }
}