use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::io::prelude::*; use crate::client::guard; use crate::client; use std::thread; use std::time::Duration; use crate::protocol; use crate::conf; pub fn start(servers: Arc>){ let listener = TcpListener::bind(String::from("0.0.0.0:") + servers.read().unwrap().get_port()).unwrap(); let guard = Arc::new(RwLock::new(guard::Guard::new())); for stream in listener.incoming() { if guard.read().unwrap().can_add(){ match stream { Ok(stream) => { let g = guard.clone(); let s = servers.clone(); thread::spawn(|| read_connection(stream, s , g)); }, Err(_e) => println!("{}",_e), } } } } fn read_connection(mut stream: TcpStream, servers: Arc>, guard: Arc> ) { let mut buf: [u8; 256] = [1; 256]; stream.set_read_timeout(Some(Duration::from_millis(5000))); let leng = match stream.read(&mut buf) { Ok(l) => l, Err(_e) => return, }; let hs = protocol::HandShake::new(&mut buf[.. leng]); if hs.is_handshake() { //Filtra los ping, solo controlamos los handshakes conect_server(servers, hs, stream, guard); } } fn conect_server(servers: Arc>, mut hs: protocol::HandShake, stream: TcpStream, guard: Arc>){ match servers.read().unwrap().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.write().unwrap().add_thread(c1.start_proxy()); }, None => println!("No server found for {}", hs.get_host_name()) } }