remove warnings

This commit is contained in:
2025-12-27 01:34:39 +00:00
parent 0be47b8b88
commit 2cf57de885
11 changed files with 441 additions and 395 deletions

2
.gitignore vendored
View File

@@ -1 +1,3 @@
target/ target/
config/mrprox.conf
config/mrprox_servers.conf

337
Cargo.lock generated
View File

@@ -3,128 +3,201 @@
version = 3 version = 3
[[package]] [[package]]
name = "atty" name = "aho-corasick"
version = "0.2.14" version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [ dependencies = [
"hermit-abi", "memchr",
"libc",
"winapi",
] ]
[[package]] [[package]]
name = "autocfg" name = "anstream"
version = "1.1.0" version = "0.6.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" checksum = "64e15c1ab1f89faffbf04a634d5e1962e9074f2741eef6d97f3c4e322426d526"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "colored"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd"
dependencies = [ dependencies = [
"atty", "anstyle",
"lazy_static", "anstyle-parse",
"winapi", "anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
] ]
[[package]]
name = "anstyle"
version = "1.0.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bec1de6f59aedf83baf9ff929c98f2ad654b97c9510f4e70cf6f661d49fd5b1"
[[package]]
name = "anstyle-parse"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb47de1e80c2b463c735db5b217a0ddc39d612e7ac9e2e96a5aed1f57616c1cb"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d36fc52c7f6c869915e99412912f22093507da8d9e942ceaf66fe4b7c14422a"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bf74e1b6e971609db8ca7a9ce79fd5768ab6ae46441c572e46cf596f59e57f8"
dependencies = [
"anstyle",
"windows-sys",
]
[[package]]
name = "colorchoice"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fd119d74b830634cea2a0f58bbd0d54540518a14397557951e79340abc28c0"
[[package]]
name = "env_filter"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f2c92ceda6ceec50f43169f9ee8424fe2db276791afde7b2cd8bc084cb376ab"
dependencies = [
"log",
"regex",
]
[[package]]
name = "env_logger"
version = "0.11.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13fa619b91fb2381732789fc5de83b45675e882f66623b7d8cb4f643017018d"
dependencies = [
"anstream",
"anstyle",
"env_filter",
"humantime",
"log",
]
[[package]]
name = "equivalent"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.12.3" version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
[[package]] [[package]]
name = "hermit-abi" name = "humantime"
version = "0.1.19" version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "indexmap" name = "indexmap"
version = "1.9.1" version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" checksum = "68b900aa2f7301e21c36462b170ee99994de34dff39a4a6a528e80e7376d07e5"
dependencies = [ dependencies = [
"autocfg", "equivalent",
"hashbrown", "hashbrown",
] ]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf"
[[package]] [[package]]
name = "itoa" name = "itoa"
version = "1.0.4" version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc"
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.144"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1"
[[package]] [[package]]
name = "log" name = "log"
version = "0.4.17" version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
dependencies = [
"cfg-if", [[package]]
] name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]] [[package]]
name = "minecraft_proxy" name = "minecraft_proxy"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"env_logger",
"log", "log",
"serde", "serde",
"serde_yaml", "serde_yaml",
"simple_logger",
]
[[package]]
name = "num_threads"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
dependencies = [
"libc",
] ]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.47" version = "1.0.86"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77"
dependencies = [ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.21" version = "1.0.37"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "regex"
version = "1.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b"
[[package]] [[package]]
name = "ryu" name = "ryu"
version = "1.0.11" version = "1.0.11"
@@ -133,18 +206,18 @@ checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09"
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.147" version = "1.0.210"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965" checksum = "c8e3592472072e6e22e0a54d5904d9febf8508f65fb8552499a1abc7d1078c3a"
dependencies = [ dependencies = [
"serde_derive", "serde_derive",
] ]
[[package]] [[package]]
name = "serde_derive" name = "serde_derive"
version = "1.0.147" version = "1.0.210"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852" checksum = "243902eda00fad750862fc144cea25caca5e20d615af0a81bee94ca738f1df1f"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@@ -153,9 +226,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_yaml" name = "serde_yaml"
version = "0.9.14" version = "0.9.34+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d232d893b10de3eb7258ff01974d6ee20663d8e833263c99409d4b13a0209da" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [ dependencies = [
"indexmap", "indexmap",
"itoa", "itoa",
@@ -164,59 +237,17 @@ dependencies = [
"unsafe-libyaml", "unsafe-libyaml",
] ]
[[package]]
name = "simple_logger"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e78beb34673091ccf96a8816fce8bfd30d1292c7621ca2bcb5f2ba0fae4f558d"
dependencies = [
"atty",
"colored",
"log",
"time",
"windows-sys",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.103" version = "2.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" checksum = "89132cd0bf050864e1d38dc3bbc07a0eb8e7530af26344d3d2bbbef83499f590"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "time"
version = "0.3.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f3403384eaacbca9923fa06940178ac13e4edb725486d70e8e15881d0c836cc"
dependencies = [
"itoa",
"libc",
"num_threads",
"serde",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb"
[[package]]
name = "time-macros"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "372950940a5f07bf38dbe211d7283c9e6d7327df53794992d293e534c733d09b"
dependencies = [
"time-core",
]
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.5" version = "1.0.5"
@@ -225,41 +256,35 @@ checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3"
[[package]] [[package]]
name = "unsafe-libyaml" name = "unsafe-libyaml"
version = "0.2.4" version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1e5fa573d8ac5f1a856f8d7be41d390ee973daf97c806b2c1a465e4e1406e68" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861"
[[package]] [[package]]
name = "winapi" name = "utf8parse"
version = "0.3.9" version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
dependencies = [
"winapi-i686-pc-windows-gnu",
"winapi-x86_64-pc-windows-gnu",
]
[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.42.0" version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [ dependencies = [
"windows_aarch64_gnullvm", "windows_aarch64_gnullvm",
"windows_aarch64_msvc", "windows_aarch64_msvc",
"windows_i686_gnu", "windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc", "windows_i686_msvc",
"windows_x86_64_gnu", "windows_x86_64_gnu",
"windows_x86_64_gnullvm", "windows_x86_64_gnullvm",
@@ -268,42 +293,48 @@ dependencies = [
[[package]] [[package]]
name = "windows_aarch64_gnullvm" name = "windows_aarch64_gnullvm"
version = "0.42.2" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]] [[package]]
name = "windows_aarch64_msvc" name = "windows_aarch64_msvc"
version = "0.42.2" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]] [[package]]
name = "windows_i686_gnu" name = "windows_i686_gnu"
version = "0.42.2" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]] [[package]]
name = "windows_i686_msvc" name = "windows_i686_msvc"
version = "0.42.2" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]] [[package]]
name = "windows_x86_64_gnu" name = "windows_x86_64_gnu"
version = "0.42.2" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]] [[package]]
name = "windows_x86_64_gnullvm" name = "windows_x86_64_gnullvm"
version = "0.42.2" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]] [[package]]
name = "windows_x86_64_msvc" name = "windows_x86_64_msvc"
version = "0.42.2" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

View File

@@ -4,10 +4,10 @@ version = "0.1.0"
edition = "2021" edition = "2021"
[dependencies] [dependencies]
serde = { version = "*", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_yaml = "*" serde_yaml = "0.9"
log = "*" log = "0.4"
simple_logger = "*" env_logger = "0.11"
[profile.release] [profile.release]
lto = true lto = true

View File

@@ -1,7 +1,7 @@
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use std::thread; use std::thread;
const MAX_THREADS : usize = 200; const MAX_THREADS: usize = 200;
pub struct Guard { pub struct Guard {
cont: Arc<RwLock<usize>>, cont: Arc<RwLock<usize>>,
@@ -9,8 +9,7 @@ pub struct Guard {
impl Guard { impl Guard {
pub fn new() -> Self { pub fn new() -> Self {
Self{ Self {
//threads: HashMap::new(),
cont: Arc::new(RwLock::new(0)), cont: Arc::new(RwLock::new(0)),
} }
} }
@@ -19,23 +18,26 @@ impl Guard {
*self.cont.read().unwrap() < MAX_THREADS *self.cont.read().unwrap() < MAX_THREADS
} }
pub fn add_thread(&mut self, pub fn add_thread(
threads: (thread::JoinHandle<()>, thread::JoinHandle<()>))-> bool { &mut self,
threads: (thread::JoinHandle<()>, thread::JoinHandle<()>),
) -> bool {
if self.can_add() { if self.can_add() {
//self.threads.insert(id, threads);
*self.cont.write().unwrap() += 1; *self.cont.write().unwrap() += 1;
let cont: Arc<RwLock<usize>> = self.cont.clone(); let cont: Arc<RwLock<usize>> = self.cont.clone();
thread::spawn(move || {Self::whatch_client(cont, threads)}); thread::spawn(move || Self::whatch_client(cont, threads));
return true; return true;
} else { } else {
false false
} }
} }
fn whatch_client(cont: Arc<RwLock<usize>>, fn whatch_client(
threads: (thread::JoinHandle<()>, thread::JoinHandle<()>)){ cont: Arc<RwLock<usize>>,
threads.0.join(); threads: (thread::JoinHandle<()>, thread::JoinHandle<()>),
threads.1.join(); ) {
_ = threads.0.join();
_ = threads.1.join();
*cont.write().unwrap() -= 1; *cont.write().unwrap() -= 1;
} }
} }

View File

@@ -1,71 +1,59 @@
use std::net::TcpStream;
use std::io::prelude::*; use std::io::prelude::*;
use std::thread; use std::net::TcpStream;
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use std::thread;
use crate::protocol; use crate::protocol;
pub mod guard; pub mod guard;
pub struct Client<'a>{ pub struct Client<'a> {
client: TcpStream, client: TcpStream,
server:TcpStream, server: TcpStream,
#[allow(dead_code)]
hs: protocol::HandShake<'a>, hs: protocol::HandShake<'a>,
run : Arc<RwLock<bool>>, run: Arc<RwLock<bool>>,
} }
impl<'a> Client<'a> { impl<'a> Client<'a> {
pub fn new(client: TcpStream, server: TcpStream, handshake: protocol::HandShake) -> Client{ pub fn new(client: TcpStream, server: TcpStream, handshake: protocol::HandShake) -> Client {
Client { Client {
client: client, client: client,
server: server, server: server,
hs: handshake, hs: handshake,
run: Arc::new(RwLock::new(true)), run: Arc::new(RwLock::new(true)),
//threads: None,
} }
} }
fn join_conexions(mut origin: TcpStream, fn join_conexions(mut origin: TcpStream, mut dest: TcpStream, run: Arc<RwLock<bool>>) {
mut dest: TcpStream,
run: Arc<RwLock<bool>>){
let mut buf: [u8; 200] = [0; 200]; let mut buf: [u8; 200] = [0; 200];
while *run.read().unwrap() { while *run.read().unwrap() {
let res=origin.read(&mut buf); let res = origin.read(&mut buf);
match res { match res {
Ok(leng) => { Ok(leng) => {
if leng == 0 { if leng == 0 {
*run.write().unwrap()=false; *run.write().unwrap() = false;
} }
match dest.write(&buf [.. leng]) { match dest.write(&buf[..leng]) {
Ok(_l) => {}, Ok(_l) => {}
Err(_e) => *run.write().unwrap()=false, Err(_e) => *run.write().unwrap() = false,
} }
}, }
Err(_e) => *run.write().unwrap()=false, Err(_e) => *run.write().unwrap() = false,
} }
} }
} }
pub fn start_proxy(&self) -> (thread::JoinHandle<()>, thread::JoinHandle<()>) { pub fn start_proxy(&self) -> (thread::JoinHandle<()>, thread::JoinHandle<()>) {
let c1 = self.client.try_clone().unwrap(); let c1 = self.client.try_clone().unwrap();
let s1 = self.server.try_clone().unwrap(); let s1 = self.server.try_clone().unwrap();
let r1 = self.run.clone(); let r1 = self.run.clone();
let handler1 = thread::spawn( || { let handler1 = thread::spawn(|| Self::join_conexions(s1, c1, r1));
Self::join_conexions(s1,
c1,
r1)}
);
let c2 = self.client.try_clone().unwrap(); let c2 = self.client.try_clone().unwrap();
let s2 = self.server.try_clone().unwrap(); let s2 = self.server.try_clone().unwrap();
let r2 = self.run.clone(); let r2 = self.run.clone();
let handler2 = thread::spawn( || { let handler2 = thread::spawn(|| Self::join_conexions(c2, s2, r2));
Self::join_conexions(c2,
s2,
r2)}
);
return (handler1, handler2); return (handler1, handler2);
} }

View File

@@ -1,21 +1,28 @@
use serde::{Serialize, Deserialize};
use std::fs::File;
use std::str::FromStr;
use std::io::prelude::*;
use std::collections::HashMap;
use log::{error, warn}; use log::{error, warn};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::str::FromStr;
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
macro_rules! PATH { () => { "/etc/mrproxy/" } } macro_rules! PATH {
#[cfg(not(debug_assertions))] () => {
static FILE_CONF: &str = concat!(PATH!(),"mrprox.conf"); "/etc/mrproxy/"
#[cfg(not(debug_assertions))] };
static FILE_SERVERS: &str = concat!(PATH!(),"mrprox_servers.conf"); }
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
static FILE_CONF: &str = "mrprox.conf"; macro_rules! PATH {
#[cfg(debug_assertions)] () => {
static FILE_SERVERS: &str = "mrprox_servers.conf"; "config/"
};
}
static FILE_CONF: &str = concat!(PATH!(), "mrprox.conf");
static FILE_SERVERS: &str = concat!(PATH!(), "mrprox_servers.conf");
const DEF_PORT: u16 = 25565; const DEF_PORT: u16 = 25565;
@@ -23,14 +30,14 @@ const TCP_TYPE: &str = "TCP";
const UNIX_TYPE: &str = "UNIX"; const UNIX_TYPE: &str = "UNIX";
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ConfFile{ pub struct ConfFile {
ip: String, ip: String,
port: String, port: String,
conf: ConfServer, conf: ConfServer,
} }
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ConfServer{ pub struct ConfServer {
sock_type: String, sock_type: String,
path: Option<String>, path: Option<String>,
ip: Option<String>, ip: Option<String>,
@@ -38,56 +45,65 @@ pub struct ConfServer{
} }
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
pub struct ServerData{ pub struct ServerData {
pub domain: String, pub domain: String,
pub ip: String, pub ip: String,
} }
pub struct Config{ pub struct Config {
l_servers : HashMap<String, String>, l_servers: HashMap<String, String>,
port: String, port: String,
ip: String, ip: String,
conf: ConfServer, conf: ConfServer,
} }
pub fn generate_conf_from_file() -> ConfFile{ pub fn generate_conf_from_file() -> ConfFile {
match File::open(&FILE_CONF) { match File::open(&FILE_CONF) {
Ok(mut f) => { Ok(mut f) => {
let mut s = String::new(); let mut s = String::new();
f.read_to_string(&mut s).unwrap(); f.read_to_string(&mut s).unwrap();
match serde_yaml::from_str(&s) { match serde_yaml::from_str(&s) {
Ok(result) => result, Ok(result) => result,
Err(e) => {error!("Config file malformed: {}",e); panic!("{}", e);}, Err(e) => {
error!("Config file malformed: {}", e);
panic!("{}", e);
}
} }
} }
Err(e) => {error!("Error open config file: {}",e); panic!("{}",e)} Err(e) => {
error!("Error open config file: {}", e);
panic!("{}", e)
}
} }
} }
pub fn generate_slist_from_file() -> Vec<ServerData>{ pub fn generate_slist_from_file() -> Vec<ServerData> {
match File::open(&FILE_SERVERS){ match File::open(&FILE_SERVERS) {
Ok(mut f) => { Ok(mut f) => {
let mut s = String::new(); let mut s = String::new();
f.read_to_string(&mut s).unwrap(); f.read_to_string(&mut s).unwrap();
match serde_yaml::from_str(&s) { match serde_yaml::from_str(&s) {
Ok(result) => result, Ok(result) => result,
Err(e) => { Err(e) => {
warn!("IPs list file malformed; creating new one\nerror: {}",e); warn!("IPs list file malformed; creating new one\nerror: {}", e);
Vec::new() Vec::new()
}, }
} }
} }
Err(e) => { Err(e) => {
warn!("IPs list file can't be open; creating new one \nerror: {}",e); warn!(
"IPs list file can't be open; creating new one \nerror: {}",
e
);
Vec::new() Vec::new()
}, }
} }
} }
impl Config { impl Config {
pub fn new() -> Self { pub fn new() -> Self {
let yaml_conf = generate_conf_from_file(); let yaml_conf = generate_conf_from_file();
Self{ Self {
l_servers: Self::get_servers(&generate_slist_from_file()), l_servers: Self::get_servers(&generate_slist_from_file()),
port: yaml_conf.port, port: yaml_conf.port,
ip: yaml_conf.ip, ip: yaml_conf.ip,
@@ -95,8 +111,8 @@ impl Config {
} }
} }
pub fn add(&mut self, server: ServerData) -> bool{ pub fn add(&mut self, server: ServerData) -> bool {
match self.l_servers.insert(server.domain, server.ip){ match self.l_servers.insert(server.domain, server.ip) {
Some(_s) => true, //Modified instead of added Some(_s) => true, //Modified instead of added
None => false, None => false,
} }
@@ -109,89 +125,100 @@ impl Config {
} }
} }
pub fn flush(&self){ pub fn flush(&self) -> Result<(), Box<dyn Error>> {
let servers = Vec::from_iter(self.l_servers.iter() let servers = Vec::from_iter(self.l_servers.iter().map(|(x, y)| ServerData {
.map(|(x, y)| ServerData{domain: (*x).clone(), ip: (*y).clone()})); domain: (*x).clone(),
let mut file = File::create(FILE_SERVERS).unwrap(); ip: (*y).clone(),
file.write(&serde_yaml::to_string(&servers).unwrap().into_bytes()); }));
file.flush(); let mut file = File::create(FILE_SERVERS)?;
_ = file.write(&serde_yaml::to_string(&servers)?.into_bytes());
_ = file.flush();
Ok(())
} }
fn get_servers(file: &Vec<ServerData>) -> HashMap<String, String> { fn get_servers(file: &Vec<ServerData>) -> HashMap<String, String> {
let mut ret = HashMap::new(); let mut ret = HashMap::new();
for j in file{ for j in file {
ret.insert(j.domain.clone(),j.ip.clone()); ret.insert(j.domain.clone(), j.ip.clone());
} }
ret ret
} }
pub fn get_host(&self, host: &String) -> Option<(&String, &String)>{ pub fn get_host(&self, host: &String) -> Option<(&String, &String)> {
self.l_servers.get_key_value(host) self.l_servers.get_key_value(host)
} }
pub fn get_server(&self, host: &String) -> Option<(String, u16)>{ pub fn get_server(&self, host: &String) -> Option<(String, u16)> {
let raw: Vec<&str> = let raw: Vec<&str> = match self.get_host(host) {
match self.get_host(host){
Some(h) => h.1.split(":").collect(), Some(h) => h.1.split(":").collect(),
None => return None, None => return None,
}; };
match raw.len() { match raw.len() {
1 => Some((String::from(raw[0]),DEF_PORT)), 1 => Some((String::from(raw[0]), DEF_PORT)),
2 => { 2 => match FromStr::from_str(raw[1]) {
match FromStr::from_str(raw[1]) { Ok(p) => Some((String::from(raw[0]), p)),
Ok(p) => Some((String::from(raw[0]),p)), Err(_e) => None,
Err(_e) => None,
}
}, },
_=> None, _ => None,
} }
} }
pub fn get_port(&self) -> &String{ #[allow(dead_code)]
pub fn get_port(&self) -> &String {
&self.port &self.port
} }
pub fn get_ip(&self) -> &String{ #[allow(dead_code)]
pub fn get_ip(&self) -> &String {
&self.ip &self.ip
} }
pub fn get_port_conf(&self) -> &String{ #[allow(dead_code)]
pub fn get_port_conf(&self) -> &String {
match self.conf.sock_type.as_str() { match self.conf.sock_type.as_str() {
TCP_TYPE => &self.conf.port.as_ref().unwrap(), TCP_TYPE => &self.conf.port.as_ref().unwrap(),
_=> {error!("Only tcp types have port"); panic!("Only tcp types have port")}, _ => {
error!("Only tcp types have port");
panic!("Only tcp types have port")
}
} }
} }
pub fn get_conf_ip(&self) -> &String{ #[allow(dead_code)]
pub fn get_conf_ip(&self) -> &String {
match self.conf.sock_type.as_str() { match self.conf.sock_type.as_str() {
TCP_TYPE => &self.conf.ip.as_ref().unwrap(), TCP_TYPE => &self.conf.ip.as_ref().unwrap(),
_=> {error!("Only tcp types have IP"); panic!("Only tcp types have IP")}, _ => {
error!("Only tcp types have IP");
panic!("Only tcp types have IP")
}
} }
} }
pub fn get_bindeable_ip(&self) -> String { pub fn get_bindeable_ip(&self) -> String {
build_bindeable_ip(&self.ip,&self.port) build_bindeable_ip(&self.ip, &self.port)
} }
pub fn get_bindeable_conf(&self) -> String { pub fn get_bindeable_conf(&self) -> String {
match self.conf.sock_type.as_str() { match self.conf.sock_type.as_str() {
TCP_TYPE => build_bindeable_ip( TCP_TYPE => build_bindeable_ip(
self.conf.ip.as_ref().unwrap(), self.conf.ip.as_ref().unwrap(),
self.conf.port.as_ref().unwrap() self.conf.port.as_ref().unwrap(),
), ),
UNIX_TYPE => self.conf.path.as_ref().unwrap().to_string(), UNIX_TYPE => self.conf.path.as_ref().unwrap().to_string(),
_=> {error!("Invalid type"); panic!("Invalid type")}, _ => {
error!("Invalid type");
panic!("Invalid type")
}
} }
} }
pub fn get_conf_type(&self) -> &String{ pub fn get_conf_type(&self) -> &String {
&self.conf.sock_type &self.conf.sock_type
} }
} }
fn build_bindeable_ip(ip: &String, port: &String) -> String{ fn build_bindeable_ip(ip: &String, port: &String) -> String {
format!("{}:{}",ip,port) format!("{}:{}", ip, port)
} }

View File

@@ -1,22 +1,20 @@
use std::thread;
//use server_conf::server_conf;
use std::sync::{Arc, RwLock};
use log::info; use log::info;
use simple_logger::SimpleLogger; use std::sync::{Arc, RwLock};
use std::thread;
mod client; mod client;
mod conf; mod conf;
mod server_conf;
mod protocol; mod protocol;
mod server_conf;
mod server_proxy; mod server_proxy;
fn main() { fn main() {
SimpleLogger::new().init().unwrap(); env_logger::init();
info!("start server"); info!("start server");
let servers = Arc::new(RwLock::new(conf::Config::new())); let servers = Arc::new(RwLock::new(conf::Config::new()));
let s1 = servers.clone(); let s1 = servers.clone();
let s2 = servers.clone(); let s2 = servers.clone();
let stop1 = thread::spawn(|| server_proxy::start(s1)); let stop1 = thread::spawn(|| server_proxy::start(s1));
let stop2 = thread::spawn(|| server_conf::server::start(s2)); let stop2 = thread::spawn(|| server_conf::server::start(s2));
stop1.join(); _ = stop1.join();
stop2.join(); _ = stop2.join();
} }

View File

@@ -5,8 +5,8 @@ pub struct HandShake<'a> {
datagram: &'a mut [u8], datagram: &'a mut [u8],
} }
impl<'a> HandShake<'a>{ impl<'a> HandShake<'a> {
pub fn new(data: &'a mut[u8]) -> Self { pub fn new(data: &'a mut [u8]) -> Self {
let len_pack = data[0]; let len_pack = data[0];
let len_dom = data[4]; let len_dom = data[4];
Self { Self {
@@ -18,28 +18,28 @@ impl<'a> HandShake<'a>{
} }
pub fn get_host_name(&self) -> String { pub fn get_host_name(&self) -> String {
String::from_utf8(self.datagram[5 .. ((self.len_dom+5) as usize)].to_vec()).unwrap() String::from_utf8(self.datagram[5..((self.len_dom + 5) as usize)].to_vec()).unwrap()
} }
#[allow(dead_code)]
pub fn get_port(&self) -> u16 { pub fn get_port(&self) -> u16 {
u16::from_be_bytes([(self.datagram[(self.len_pack - 2) as usize]), u16::from_be_bytes([
(self.datagram[(self.len_pack - 1) as usize])]) (self.datagram[(self.len_pack - 2) as usize]),
(self.datagram[(self.len_pack - 1) as usize]),
])
} }
pub fn replace_port(&mut self, n_port: u16){ pub fn replace_port(&mut self, n_port: u16) {
let s_port = n_port.to_ne_bytes(); let s_port = n_port.to_ne_bytes();
self.datagram[self.port_pos]=s_port[1]; self.datagram[self.port_pos] = s_port[1];
self.datagram[self.port_pos+1]=s_port[0]; self.datagram[self.port_pos + 1] = s_port[0];
} }
pub fn get_raw(&self) -> &[u8] {
pub fn get_raw(&self) -> &[u8]{
self.datagram self.datagram
} }
pub fn is_handshake(&self) -> bool { pub fn is_handshake(&self) -> bool {
(self.datagram[0] == self.len_pack) && (self.datagram[0] == self.len_pack) && (self.len_dom + 7 == self.len_pack)
(self.len_dom + 7 == self.len_pack)
} }
} }

View File

@@ -1,7 +1,8 @@
use std::io::prelude::*;
use crate::conf; use crate::conf;
use std::sync::{Arc, RwLock};
use log::{error, warn}; use log::{error, warn};
use std::error::Error;
use std::io::prelude::*;
use std::sync::{Arc, RwLock};
const OP_ADD: u8 = 0; const OP_ADD: u8 = 0;
const OP_DEL: u8 = 1; const OP_DEL: u8 = 1;
@@ -16,82 +17,89 @@ const RE_KO: u8 = 1;
pub struct Conexion<TSocket: Read + Write> { pub struct Conexion<TSocket: Read + Write> {
conf: Arc<RwLock<conf::Config>>, conf: Arc<RwLock<conf::Config>>,
stream: TSocket, stream: TSocket,
buf:[u8; 256], buf: [u8; 256],
exit: bool, exit: bool,
} }
impl<TSocket: Read + Write> Conexion<TSocket> { impl<TSocket: Read + Write> Conexion<TSocket> {
pub fn new(conf: Arc<RwLock<conf::Config>>, stream: TSocket) -> Self { pub fn new(conf: Arc<RwLock<conf::Config>>, stream: TSocket) -> Self {
Self{ Self {
conf: conf, conf: conf,
stream: stream, stream: stream,
buf: [1; 256], buf: [1; 256],
exit: false, exit: false,
} }
} }
pub fn process_reques(&mut self) { pub fn process_reques(&mut self) {
let mut state: [u8; 1] = [1; 1]; let mut state: [u8; 1] = [1; 1];
while !self.exit { while !self.exit {
match self.stream.read_exact(&mut state){ match self.stream.read_exact(&mut state) {
Ok(len) => self.check_state(state[0]), Ok(_len) => _ = self.check_state(state[0]),
Err(e) => {self.exit=true; error!("{}", e);}, Err(e) => {
self.exit = true;
error!("{}", e);
}
}
} }
}
} }
fn read_domain_info(&mut self) -> fn read_domain_info(&mut self) -> Result<conf::ServerData, std::io::Error> {
Result<conf::ServerData, std::io::Error>{ let _len = self.stream.read(&mut self.buf)?;
let mut len = self.stream.read(&mut self.buf)?;
let end_domain = (self.buf[0] + 1) as usize; let end_domain = (self.buf[0] + 1) as usize;
let start_ip = end_domain + 1 as usize; let start_ip = end_domain + 1 as usize;
let end_ip = self.buf[end_domain] as usize + start_ip; let end_ip = self.buf[end_domain] as usize + start_ip;
let domain = String::from_utf8(self.buf[1 .. end_domain].to_vec()).unwrap(); let domain = String::from_utf8(self.buf[1..end_domain].to_vec()).unwrap();
let ip = String::from_utf8(self.buf[start_ip .. end_ip].to_vec()).unwrap(); let ip = String::from_utf8(self.buf[start_ip..end_ip].to_vec()).unwrap();
Ok(conf::ServerData{ Ok(conf::ServerData {
domain: domain, domain: domain,
ip: ip, ip: ip,
}) })
} }
fn read_unique_info(&mut self) -> fn read_unique_info(&mut self) -> Result<String, std::io::Error> {
Result<String, std::io::Error>{ self.stream.read_exact(&mut self.buf[0..1])?;
self.stream.read_exact(&mut self.buf[0 .. 1])?;
let len = self.buf[0] as usize; let len = self.buf[0] as usize;
self.stream.read_exact(&mut self.buf[0 .. len])?; self.stream.read_exact(&mut self.buf[0..len])?;
Ok(String::from_utf8(self.buf[0 .. len].to_vec()).unwrap()) Ok(String::from_utf8(self.buf[0..len].to_vec()).unwrap())
} }
fn check_state(&mut self, state: u8) { fn check_state(&mut self, state: u8) -> Result<(), Box<dyn Error + '_>> {
match state{ match state {
OP_ADD => { OP_ADD => match self.read_domain_info() {
match self.read_domain_info() { Ok(sd) => {
Ok(sd) => { match self.conf.write()?.add(sd) {
match self.conf.write().unwrap().add(sd) { true => self.stream.write(&[RE_MOD])?,
true => self.stream.write(&[RE_MOD]), false => self.stream.write(&[RE_ADD])?,
false => self.stream.write(&[RE_ADD]), };
}; _ = self.conf.read()?.flush();
self.conf.read().unwrap().flush(); }
}, Err(e) => {
Err(e) => {self.exit=true; warn!("{}", e);}, self.exit = true;
warn!("{}", e);
} }
}, },
OP_DEL => match self.read_unique_info(){ OP_DEL => match self.read_unique_info() {
Ok(domain) => { Ok(domain) => {
match self.conf.write().unwrap().del(domain){ match self.conf.write()?.del(domain) {
true => { true => {
self.stream.write(&[RE_OK]); self.stream.write(&[RE_OK])?;
}, }
false => {self.stream.write(&[RE_KO]);}, false => {
self.stream.write(&[RE_KO])?;
}
}; };
self.conf.read().unwrap().flush(); _ = self.conf.read().unwrap().flush();
}
Err(e) => {
self.exit = true;
error!("{}", e);
} }
Err(e) => {self.exit=true; error!("{}", e);},
}, },
OP_EXIT => self.exit=true, OP_EXIT => self.exit = true,
_=> warn!("no recognice option: {}", state), _ => warn!("no recognice option: {}", state),
} };
Ok(())
} }
} }

View File

@@ -1,77 +1,68 @@
use std::io::{Error, ErrorKind};
use std::net::TcpListener; use std::net::TcpListener;
use std::net::TcpStream; use std::net::TcpStream;
use std::os::unix::net::UnixListener; use std::os::unix::net::UnixListener;
use std::os::unix::net::UnixStream; use std::os::unix::net::UnixStream;
use std::io::{Error, ErrorKind};
use log::{warn};
pub const TCP_LIS : u8 = 1; pub const TCP_LIS: u8 = 1;
pub const UNIX_LIS : u8 = 2; pub const UNIX_LIS: u8 = 2;
pub const ERROR_LIS : u8 = 0; pub const ERROR_LIS: u8 = 0;
pub trait RWTrait: std::io::Read + std::io::Write + Send {} pub trait RWTrait: std::io::Read + std::io::Write + Send {}
impl RWTrait for TcpStream {} impl RWTrait for TcpStream {}
impl RWTrait for UnixStream {} impl RWTrait for UnixStream {}
pub struct GenericListener { pub struct GenericListener {
tcp_lis : Option<TcpListener>, tcp_lis: Option<TcpListener>,
unix_lis : Option<UnixListener>, unix_lis: Option<UnixListener>,
type_lis : u8, type_lis: u8,
} }
impl GenericListener { impl GenericListener {
fn new_tcp(listener: TcpListener) -> Self{ fn new_tcp(listener: TcpListener) -> Self {
GenericListener{ GenericListener {
tcp_lis: Some(listener), tcp_lis: Some(listener),
unix_lis: None, unix_lis: None,
type_lis: TCP_LIS, type_lis: TCP_LIS,
} }
} }
fn new_unix(listener: UnixListener) -> Self{ fn new_unix(listener: UnixListener) -> Self {
GenericListener{ GenericListener {
tcp_lis: None, tcp_lis: None,
unix_lis: Some(listener), unix_lis: Some(listener),
type_lis: UNIX_LIS, type_lis: UNIX_LIS,
} }
} }
pub fn bind(address: String, type_lis: u8) -> Result<Self, String>{ pub fn bind(address: String, type_lis: u8) -> Result<Self, String> {
let ret = match type_lis { let ret = match type_lis {
TCP_LIS => Self::new_tcp( TCP_LIS => Self::new_tcp(match TcpListener::bind(address) {
match TcpListener::bind(address) { Ok(s) => s,
Ok(s) => s, Err(e) => return Err(e.to_string()),
Err(e) => return Err(e.to_string()), }),
}), UNIX_LIS => Self::new_unix(match UnixListener::bind(address) {
UNIX_LIS => Self::new_unix( Ok(s) => s,
match UnixListener::bind(address){ Err(e) => return Err(e.to_string()),
Ok(s) => s, }),
Err(e) => return Err(e.to_string()),
}),
_ => return Err("No valid option".to_string()), _ => return Err("No valid option".to_string()),
}; };
Ok(ret) Ok(ret)
} }
pub fn accept(&self) -> Result<Box<dyn RWTrait>, Error> {
pub fn accept(&self) -> Result<Box<dyn RWTrait>,Error> {
match self.type_lis { match self.type_lis {
TCP_LIS => Ok(Box::new(self.tcp_lis.as_ref().unwrap().accept()?.0)), TCP_LIS => Ok(Box::new(self.tcp_lis.as_ref().unwrap().accept()?.0)),
UNIX_LIS => Ok(Box::new(self.unix_lis.as_ref().unwrap().accept()?.0)), UNIX_LIS => Ok(Box::new(self.unix_lis.as_ref().unwrap().accept()?.0)),
_=> Err(Error::new(ErrorKind::Other, "Unexpected type")) _ => Err(Error::new(ErrorKind::Other, "Unexpected type")),
} }
} }
pub fn string_top_type(s: &String) -> u8 { pub fn string_top_type(s: &String) -> u8 {
match (*s).as_str(){ match (*s).as_str() {
"TCP" => TCP_LIS, "TCP" => TCP_LIS,
"UNIX" => UNIX_LIS, "UNIX" => UNIX_LIS,
&_ => ERROR_LIS, &_ => ERROR_LIS,
} }
} }
} }

View File

@@ -1,65 +1,64 @@
use crate::client;
use crate::client::guard;
use crate::conf;
use crate::protocol;
use log::{error, info};
use std::io::prelude::*;
use std::net::{TcpListener, TcpStream}; use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, RwLock}; use std::sync::{Arc, RwLock};
use std::io::prelude::*;
use crate::client::guard;
use crate::client;
use std::thread; use std::thread;
use std::time::Duration; use std::time::Duration;
use crate::protocol;
use crate::conf;
use log::{error, info};
pub fn start(servers: Arc<RwLock<conf::Config>>){ pub fn start(servers: Arc<RwLock<conf::Config>>) {
let listener = TcpListener::bind( let listener = TcpListener::bind(servers.read().unwrap().get_bindeable_ip()).unwrap();
servers.read().unwrap().get_bindeable_ip()
).unwrap();
let guard = Arc::new(RwLock::new(guard::Guard::new())); let guard = Arc::new(RwLock::new(guard::Guard::new()));
for stream in listener.incoming() { for stream in listener.incoming() {
if guard.read().unwrap().can_add(){ if guard.read().unwrap().can_add() {
match stream { match stream {
Ok(stream) => { Ok(stream) => {
let g = guard.clone(); let g = guard.clone();
let s = servers.clone(); let s = servers.clone();
thread::spawn(|| read_connection(stream, s , g)); thread::spawn(|| read_connection(stream, s, g));
}, }
Err(_e) => error!("{}",_e), Err(_e) => error!("{}", _e),
} }
} }
} }
} }
fn read_connection(mut stream: TcpStream, fn read_connection(
servers: Arc<RwLock<conf::Config>>, mut stream: TcpStream,
guard: Arc<RwLock<guard::Guard>> ) { servers: Arc<RwLock<conf::Config>>,
guard: Arc<RwLock<guard::Guard>>,
) {
let mut buf: [u8; 256] = [1; 256]; let mut buf: [u8; 256] = [1; 256];
stream.set_read_timeout(Some(Duration::from_millis(5000))); _ = stream.set_read_timeout(Some(Duration::from_millis(5000)));
let leng = match stream.read(&mut buf) { let leng = match stream.read(&mut buf) {
Ok(l) => l, Ok(l) => l,
Err(_e) => return, Err(_e) => return,
}; };
let hs = protocol::HandShake::new(&mut buf[.. leng]); let hs = protocol::HandShake::new(&mut buf[..leng]);
if hs.is_handshake() { //Filtra los ping, solo controlamos los handshakes if hs.is_handshake() {
conect_server(servers, hs, stream, guard); //Filtra los ping, solo controlamos los handshakes
conect_server(servers, hs, stream, guard);
} }
} }
fn conect_server(servers: Arc<RwLock<conf::Config>>, fn conect_server(
mut hs: protocol::HandShake, servers: Arc<RwLock<conf::Config>>,
stream: TcpStream, mut hs: protocol::HandShake,
guard: Arc<RwLock<guard::Guard>>){ stream: TcpStream,
guard: Arc<RwLock<guard::Guard>>,
) {
match servers.read().unwrap().get_server(&hs.get_host_name()) { match servers.read().unwrap().get_server(&hs.get_host_name()) {
Some(s) => { Some(s) => {
hs.replace_port(s.1); hs.replace_port(s.1);
let mut sstream = TcpStream::connect(s.0 + ":" + &s.1.to_string()).unwrap(); let mut sstream = TcpStream::connect(s.0 + ":" + &s.1.to_string()).unwrap();
sstream.write(hs.get_raw()); _ = sstream.write(hs.get_raw());
let c1 = client::Client::new(stream,sstream, hs); let c1 = client::Client::new(stream, sstream, hs);
guard.write().unwrap().add_thread(c1.start_proxy()); guard.write().unwrap().add_thread(c1.start_proxy());
}, }
None => info!("No server found for {}", hs.get_host_name()) None => info!("No server found for {}", hs.get_host_name()),
} }
} }