65 lines
1.9 KiB
Rust
65 lines
1.9 KiB
Rust
use std::net::{TcpListener, TcpStream};
|
|
use std::sync::{Arc, RwLock};
|
|
use std::io::prelude::*;
|
|
use crate::client::guard;
|
|
use std::thread;
|
|
use std::time::Duration;
|
|
|
|
|
|
mod client;
|
|
mod conf;
|
|
mod protocol;
|
|
|
|
fn main() {
|
|
let listener = TcpListener::bind("0.0.0.0:25565").unwrap();
|
|
let servers = Arc::new(RwLock::new(conf::Servers::new()));
|
|
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<RwLock<conf::Servers>>,
|
|
guard: Arc<RwLock<guard::Guard>> ) {
|
|
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<RwLock<conf::Servers>>,
|
|
mut hs: protocol::HandShake,
|
|
stream: TcpStream,
|
|
guard: Arc<RwLock<guard::Guard>>){
|
|
|
|
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())
|
|
}
|
|
}
|
|
|