From f754030997e6f2c076d31076fcaa8ddce6c13d29 Mon Sep 17 00:00:00 2001
From: groche97 <groche97@gmail.com>
Date: Sat, 24 Sep 2022 20:49:00 +0200
Subject: [PATCH] Minor fixes and error tolerance

---
 src/client/guard.rs |  3 ---
 src/client/mod.rs   | 10 +++++++---
 src/main.rs         | 43 ++++++++++++++++++++++++++++---------------
 src/protocol/mod.rs |  4 +---
 4 files changed, 36 insertions(+), 24 deletions(-)

diff --git a/src/client/guard.rs b/src/client/guard.rs
index be26a11..a21f363 100644
--- a/src/client/guard.rs
+++ b/src/client/guard.rs
@@ -1,4 +1,3 @@
-use std::collections::HashMap;
 use std::sync::{Arc, RwLock};
 use std::thread;
 
@@ -37,8 +36,6 @@ impl Guard {
         threads: (thread::JoinHandle<()>, thread::JoinHandle<()>)){
         threads.0.join();
         threads.1.join();
-        println!("Cliente muerto {}", *cont.read().unwrap());
         *cont.write().unwrap() -= 1;
-
     }
 }
diff --git a/src/client/mod.rs b/src/client/mod.rs
index e2cf67b..e1f42f9 100644
--- a/src/client/mod.rs
+++ b/src/client/mod.rs
@@ -20,11 +20,12 @@ impl<'a> Client<'a> {
             server: Arc::new(Mutex::new(server)),
             hs: handshake,
             run: Arc::new(RwLock::new(true)),
+            //threads: None,
         }
     }
 
     pub fn to_string(&self){
-        println!("len_pack {}", self.hs.getHostName());
+        println!("len_pack {}", self.hs.get_host_name());
     }
 
     fn join_conexions_mutex(c1: Arc<Mutex<TcpStream>>,
@@ -39,10 +40,13 @@ impl<'a> Client<'a> {
                     if leng == 0 {
                         *run.write().unwrap()=false;
                     }
-                    c2.lock().unwrap().write(&buf [.. leng]);
+                    match c2.lock().unwrap().write(&buf [.. leng]) {
+                        Ok(_l) => {},
+                        Err(_e) => *run.write().unwrap()=false,
+                    }
                 },
 
-                Err(_e) => {*run.write().unwrap()=false;},
+                Err(_e) => *run.write().unwrap()=false,
             }
 
         }
diff --git a/src/main.rs b/src/main.rs
index 0aeeb72..1fccffb 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,6 +1,9 @@
 use std::net::{TcpListener, TcpStream};
 use std::io::prelude::*;
 use crate::client::guard;
+use std::thread;
+use std::time::Duration;
+
 
 mod client;
 mod conf;
@@ -10,27 +13,20 @@ fn main() {
     let listener = TcpListener::bind("127.0.0.1:25567").unwrap();
     let mut buf: [u8; 256] = [1; 256];
     let servers = conf::Servers::new();
-    let mut guard: guard::Guard = guard::Guard::new();
+    let mut guard = guard::Guard::new();
     for stream in listener.incoming() {
         if guard.can_add(){
             match stream {
                 Ok(mut stream) => {
-                    let leng = stream.read(&mut buf).unwrap();
+                    stream.set_read_timeout(Some(Duration::from_millis(5000)));
+                    //stream.set_write_timeout(Some(Duration::from_millis(5000)));
+                    let leng = match stream.read(&mut buf) {
+                        Ok(l) => l,
+                        Err(_e) => break,
+                    };
                     let mut hs = protocol::HandShake::new(&mut buf[.. leng]);
                     if hs.get_raw()[0] < 200 { //Filtra los ping, solo controlamos los handshakes
-                        match servers.get_server(&hs.getHostName()) {
-                            Some(s) => {
-                                hs.replace_port(s.1);
-                                let mut sstream = TcpStream::connect(s.0 + ":" + &s.1.to_string()).unwrap();
-                                let p_id = sstream.local_addr().unwrap().port();
-                                println!("port4: {}",sstream.peer_addr().unwrap().port());
-                                sstream.write(hs.get_raw());
-                                let c1 = client::Client::new(stream,sstream, hs);
-                                guard.add_thread(c1.start_proxy());
-                            },
-                            None => println!("No server found for{}", hs.getHostName())
-                        }
-
+                        conect_server(&servers, hs, stream, &mut guard);
                     }
                 },
 
@@ -40,3 +36,20 @@ fn main() {
     }
 }
 
+fn conect_server(servers: &conf::Servers,
+        mut hs: protocol::HandShake,
+        stream: TcpStream,
+        guard: &mut guard::Guard){
+
+    match servers.get_server(&hs.get_host_name()) {
+        Some(s) => {
+            hs.replace_port(s.1);
+            let mut sstream = TcpStream::connect(s.0 + ":" + &s.1.to_string()).unwrap();
+            sstream.write(hs.get_raw());
+            let c1 = client::Client::new(stream,sstream, hs);
+            guard.add_thread(c1.start_proxy());
+        },
+        None => println!("No server found for {}", hs.get_host_name())
+    }
+}
+
diff --git a/src/protocol/mod.rs b/src/protocol/mod.rs
index 8331e8c..2de975f 100644
--- a/src/protocol/mod.rs
+++ b/src/protocol/mod.rs
@@ -1,5 +1,3 @@
-use std::string;
-
 pub struct HandShake<'a> {
     len_pack: u8,
     len_dom: u8,
@@ -19,7 +17,7 @@ impl<'a> HandShake<'a>{
         }
     }
 
-    pub fn getHostName(&self) -> String {
+    pub fn get_host_name(&self) -> String {
         String::from_utf8(self.datagram[5 .. ((self.len_dom+5) as usize)].to_vec()).unwrap()
     }