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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
//! Structure for representing an [`Aether`] client.

pub mod authentication;
pub mod handshake;

use log::{error, trace};

use std::collections::VecDeque;
use std::convert::TryFrom;
use std::sync::{Arc, Mutex, MutexGuard};

use std::thread;
use std::time::{Duration, SystemTime};
use std::{collections::HashMap, net::SocketAddr};

use std::net::{IpAddr, Ipv4Addr, UdpSocket};

use rand::{thread_rng, Rng};

use crate::config::Config;
use crate::identity::Id;
use crate::peer::authentication::authenticate;
use crate::tracker::TrackerPacket;
use crate::{error::AetherError, link::Link, tracker::ConnectionRequest};

use self::handshake::handshake;

/// Enumeration representing different states of a connection
#[derive(Debug)]
pub enum Connection {
    /// Initialized state - connection has been initialized and is waiting to receive
    /// other peer's public identity
    Init(Initialized),
    /// Handshake state - handshake with the other peer is in progress
    Handshake,
    /// Connected state - a connection to the other peer has been established
    Connected(Box<Peer>),
    /// Failed state - a connection to the other peer had failed and would be retried
    Failed(Failure),
}

#[derive(Debug)]
pub struct Peer {
    pub uid: String,
    pub identity_number: u32,
    link: Link,
}

#[derive(Debug)]
pub struct Initialized {
    uid: String,
    socket: UdpSocket,
    identity_number: u32,
}

impl Initialized {
    pub fn new(uid: String) -> Initialized {
        Initialized {
            uid,
            socket: UdpSocket::bind(("0.0.0.0", 0)).expect("unable to create socket"),
            identity_number: 1,
        }
    }
}

#[derive(Debug)]
pub struct Failure {
    time: SystemTime,
    socket: UdpSocket,
    uid: String,
}

/// [`Aether`] is an interface used to connect to other peers as well as communicate
/// with them
pub struct Aether {
    /// Username assigned to the Aether instance
    uid: String,
    /// Identity of user
    private_id: Id,
    /// The [`UdpSocket`] to be used for communication
    socket: Arc<UdpSocket>,
    /// Queue of connection requests received
    requests: Arc<Mutex<VecDeque<ConnectionRequest>>>,
    /// Address of the tracker server
    tracker_addr: SocketAddr,
    /// List of peers related to this peer
    connections: Arc<Mutex<HashMap<String, Connection>>>,
    /// Configuration
    config: Config,
}

impl Aether {
    pub fn new(tracker_addr: SocketAddr) -> Self {
        let private_id = Id::load_or_generate().expect("Error loading identity");

        Self::new_with_id(private_id, tracker_addr)
    }

    pub fn new_with_id(id: Id, tracker_addr: SocketAddr) -> Self {
        let config = Config::get_config().expect("Error getting config");

        let uid = id.public_key_to_base64().expect("Error getting public key");

        let socket = Arc::new(UdpSocket::bind(("0.0.0.0", 0)).unwrap());
        socket
            .set_read_timeout(Some(Duration::from_millis(
                config.aether.server_retry_delay,
            )))
            .expect("Unable to set read timeout");
        Aether {
            uid,
            private_id: id,
            requests: Arc::new(Mutex::new(VecDeque::new())),
            tracker_addr,
            socket,
            connections: Arc::new(Mutex::new(HashMap::new())),
            config,
        }
    }

    pub fn get_uid(&self) -> &str {
        &self.uid
    }

    pub fn start(&self) {
        trace!("Starting aether service...");
        self.connection_poll();
        self.handle_sockets();
        self.handle_requests();
    }

    pub fn connect(&self, uid: &str) {
        let mut connections_lock = self.connections.lock().expect("Unable to lock peers");

        let is_present = (*connections_lock).get(uid).is_some();

        if !is_present {
            let initialized = Initialized::new(uid.to_string());

            (*connections_lock).insert(uid.to_string(), Connection::Init(initialized));
        }
    }

    pub fn send_to(&self, uid: &str, buf: Vec<u8>) -> Result<u8, u8> {
        let mut connections_lock = self.connections.lock().expect("unable to lock peers list");
        match (*connections_lock).get_mut(uid) {
            Some(connection) => match connection {
                Connection::Connected(peer) => {
                    peer.link.send(buf).unwrap();
                    Ok(0)
                }
                _ => Err(3),
            },

            None => Err(1),
        }
    }

    pub fn recv_from(&self, uid: &str) -> Result<Vec<u8>, AetherError> {
        let connections_lock = match self.connections.lock() {
            Ok(lock) => lock,
            Err(_) => return Err(AetherError::MutexLock("connections")),
        };

        let peer = match (*connections_lock).get(uid) {
            Some(Connection::Connected(peer)) => peer,
            _ => return Err(AetherError::NotConnected(uid.to_string())),
        };

        let receiver = peer.link.get_receiver()?;

        drop(connections_lock);

        let packet = receiver.recv()?;

        Ok(packet.payload)
    }

    pub fn wait_connection(&self, uid: &str) -> Result<u8, u8> {
        while !self.is_connected(uid) {
            thread::sleep(Duration::from_millis(
                self.config.aether.connection_check_delay,
            ));
        }
        Ok(0)
    }

    pub fn is_connected(&self, uid: &str) -> bool {
        let connections_lock = self.connections.lock().expect("unable to lock peers list");
        matches!((*connections_lock).get(uid), Some(Connection::Connected(_)))
    }

    pub fn is_connecting(&self, uid: &str) -> bool {
        let connections_lock = self
            .connections
            .lock()
            .expect("unable to lock connecting list");
        match (*connections_lock).get(uid) {
            Some(connection) => {
                !matches!(connection, Connection::Failed(_) | Connection::Connected(_))
            }
            None => false,
        }
    }

    pub fn is_initialized(&self, uid: &str) -> bool {
        let connections_lock = self
            .connections
            .lock()
            .expect("unable to lock connecting list");
        matches!((*connections_lock).get(uid), Some(Connection::Init(_)))
    }

    fn handle_sockets(&self) {
        let my_uid = self.uid.clone();
        let connections = self.connections.clone();
        let tracker_addr = self.tracker_addr;
        let config = self.config;
        thread::spawn(move || {
            loop {
                // Lock connections list
                let connections_lock = connections.lock().expect("unable to lock initialized list");

                // For each connection
                for (_, connection) in (*connections_lock).iter() {
                    // If connection is in initialized or failed state, send connection
                    // request
                    match connection {
                        Connection::Init(init) => {
                            Self::send_connection_request(
                                my_uid.clone(),
                                init.uid.clone(),
                                &init.socket,
                                tracker_addr,
                            );
                        }
                        Connection::Failed(failed) => Self::send_connection_request(
                            my_uid.clone(),
                            failed.uid.clone(),
                            &failed.socket,
                            tracker_addr,
                        ),
                        _ => {}
                    };
                }

                // Unlock initailized list
                drop(connections_lock);
                thread::sleep(Duration::from_millis(config.aether.server_poll_time));
            }
        });
    }

    fn send_connection_request(
        uid: String,
        peer_uid: String,
        socket: &UdpSocket,
        tracker_addr: SocketAddr,
    ) {
        let packet = TrackerPacket {
            username: uid,
            peer_username: peer_uid,
            identity_number: 1,
            packet_type: 2,
            req: true,
            ..Default::default()
        };

        let packet_data: Vec<u8> = Vec::try_from(packet).expect("Unable to encode packet");

        socket
            .send_to(&packet_data, tracker_addr)
            .expect("unable to send packet to server");
    }

    fn connection_poll(&self) {
        let poll_request = TrackerPacket {
            username: self.uid.clone(),
            packet_type: 3,
            req: true,
            ..Default::default()
        };

        let data_bytes: Vec<u8> = Vec::try_from(poll_request).expect("Unable to encode packet");
        let mut buf: [u8; 1024] = [0; 1024];

        let socket = self.socket.clone();
        let tracker_addr = self.tracker_addr;

        let requests = self.requests.clone();

        let config = self.config;

        thread::spawn(move || loop {
            socket
                .send_to(&data_bytes, tracker_addr)
                .expect("Unable to send to server");

            let response_data = match socket.recv(&mut buf) {
                Ok(size) => buf[..size].to_vec(),
                Err(_) => Vec::new(),
            };

            if !response_data.is_empty() {
                let response_packet =
                    TrackerPacket::try_from(response_data).expect("Unable to decode packet");

                for v in response_packet.connections {
                    let mut req_lock = requests.lock().expect("unable to lock request queue");
                    (*req_lock).push_back(v);
                }

                thread::sleep(Duration::from_millis(config.aether.server_poll_time));
            }
        });
    }

    fn handle_requests(&self) {
        let requests = self.requests.clone();
        let connections = self.connections.clone();
        let my_uid = self.uid.clone();
        let tracker_addr = self.tracker_addr;
        let config = self.config;
        let private_id = self.private_id.clone();

        thread::spawn(move || loop {
            let mut req_lock = requests.lock().expect("Unable to lock requests queue");

            // For each request received
            if let Some(request) = (*req_lock).pop_front() {
                Self::handle_request(
                    private_id.clone(),
                    request,
                    my_uid.clone(),
                    &mut connections.clone(),
                    tracker_addr,
                    &mut req_lock,
                    config,
                )
            }

            drop(req_lock);
            thread::sleep(Duration::from_micros(config.aether.poll_time_us));
        });
    }

    fn handle_request(
        private_id: Id,
        request: ConnectionRequest,
        my_uid: String,
        connections: &mut Arc<Mutex<HashMap<String, Connection>>>,
        tracker_addr: SocketAddr,
        req_lock: &mut MutexGuard<VecDeque<ConnectionRequest>>,
        config: Config,
    ) {
        let mut connections_lock = connections.lock().expect("unable to lock failed list");
        // Clone important data to pass to handshake thread
        let connections_clone = connections.clone();
        let my_uid_clone = my_uid.clone();

        let config_clone = config;

        let handshake_thread = move |init: Initialized, request: ConnectionRequest| {
            // Initailize data values for handshake
            let peer_ip = IpAddr::V4(Ipv4Addr::from(request.ip));
            let peer_addr = SocketAddr::new(peer_ip, request.port);
            let peer_uid = request.username;

            let mut success = false; // This bool DOES in fact get read and modified. Not sure why compiler doesn't recognize its usage.

            // Start handshake
            let link_result = handshake(
                private_id,
                init.socket,
                peer_addr,
                my_uid_clone.clone(),
                peer_uid.clone(),
                config_clone,
            );

            match link_result {
                Ok(link) => {
                    trace!("Handshake success");

                    match authenticate(link, peer_uid.clone(), request.identity_number, config) {
                        Ok(mut peer) => {
                            if let Err(err) = peer.link.enable_encryption() {
                                error!("Cannot enable encryption: {}", err);
                            } else {
                                let mut connections_lock =
                                    connections_clone.lock().expect("unable to lock peer list");

                                // Add connected peer to connections list
                                // with connected state
                                (*connections_lock).insert(
                                    peer_uid.clone(),
                                    Connection::Connected(Box::new(peer)),
                                );
                                success = true;
                            }
                        }
                        Err(AetherError::AuthenticationFailed(_)) => {
                            trace!("Cannot reach");
                        }
                        Err(AetherError::AuthenticationInvalid(_)) => {
                            error!("Identity could not be authenticated")
                        }
                        Err(other) => {
                            panic!("Unexpected error {}", other);
                        }
                    }
                }
                Err(e) => {
                    trace!("Handshake failed {}", e);
                }
            }

            // If unsuccessful store time of failure
            if !success {
                let mut connections_lock =
                    connections_clone.lock().expect("unable to lock peer list");

                // Add failure entry to connection list
                (*connections_lock).insert(
                    peer_uid.clone(),
                    Connection::Failed(Failure {
                        time: SystemTime::now(),
                        socket: UdpSocket::bind(("0.0.0.0", 0)).expect("unable to create socket"),
                        uid: peer_uid,
                    }),
                );
            }
        };

        // Check if connection exists in connection list
        match (*connections_lock).remove(&request.username) {
            // If initialized, start handshake
            // Initailized either since connection request was made by us first
            // Or initailized after receiving connection request from other peer
            Some(Connection::Init(init)) => {
                // Put current user in handshake state
                (*connections_lock).insert(init.uid.clone(), Connection::Handshake);

                // Create a thread to start handshake and establish connection
                thread::spawn(move || handshake_thread(init, request));
            }
            Some(Connection::Failed(failed)) => {
                let delta = thread_rng().gen_range(0..config.aether.delta_time);
                let elapsed = failed
                    .time
                    .elapsed()
                    .expect("unable to get system time")
                    .as_millis();

                // if elapsed time since the fail is greater than threshold
                // then put back in initialized state
                if elapsed > (config.aether.handshake_retry_delay + delta).into() {
                    (*connections_lock).insert(
                        failed.uid.clone(),
                        Connection::Init(Initialized {
                            uid: failed.uid,
                            socket: failed.socket,
                            identity_number: 1,
                        }),
                    );
                } else {
                    // If elapsed time is not long enough
                    // insert back into the list
                    (*connections_lock).insert(failed.uid.clone(), Connection::Failed(failed));
                }
            }
            Some(other) => {
                // If in other state, insert back the value
                (*connections_lock).insert(request.username.clone(), other);
            }
            // If not in connections (other peer is initiator)
            // Initailize the request
            None => {
                // Create new identity
                let connection = Initialized {
                    identity_number: 1,
                    socket: UdpSocket::bind(("0.0.0.0", 0)).expect("unable to create socket"),
                    uid: request.username.clone(),
                };

                let packet = TrackerPacket {
                    username: my_uid,
                    peer_username: connection.uid.clone(),
                    identity_number: connection.identity_number,
                    packet_type: 2,
                    req: true,
                    ..Default::default()
                };

                let packet_data: Vec<u8> = Vec::try_from(packet).expect("Unable to encode packet");

                connection
                    .socket
                    .send_to(&packet_data, tracker_addr)
                    .expect("unable to send packet to server");

                // Insert new initialized connection
                (*connections_lock).insert(request.username.clone(), Connection::Init(connection));

                (*req_lock).push_back(request);
            }
        }
    }
}