Skip to content

Commit a05f0e2

Browse files
committed
Улучшенная обработка ошибок
1 parent 5b0e751 commit a05f0e2

File tree

4 files changed

+81
-90
lines changed

4 files changed

+81
-90
lines changed

Cargo.toml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
[package]
22
name = "voxelproxy"
3-
version = "3.1.0"
3+
version = "3.1.1"
44
edition = "2021"
55

66
[dependencies]
7-
tokio = { version = "1.38.1", features = ["full"] }
8-
serde_json = "1.0.128"
7+
tokio = { version = "1.46.1", features = ["full"] }
8+
serde_json = "1.0.141"
99
trust-dns-resolver = "0.23.2"
1010
dialoguer = "0.11.0"
11-
reqwest = { version = "0.12.7", features = ["json"] }
11+
reqwest = { version = "0.12.22", features = ["json"] }
1212
anyhow = "1.0.98"
1313
minecraft_protocol = { git = "https://github.com/kauri-off/minecraft_protocol.git" }
1414

build.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,10 @@
11
fn main() {
2+
#[cfg(not(debug_assertions))]
23
let target = std::env::var("TARGET").unwrap_or_default();
34

4-
// Только для Windows + MSVC
5+
#[cfg(not(debug_assertions))]
56
if target.contains("windows-msvc") {
67
println!("cargo:rustc-link-arg=/ENTRY:mainCRTStartup");
78
println!("cargo:rustc-link-arg=/SUBSYSTEM:WINDOWS");
89
}
9-
10-
// Если хочешь также поддерживать gnu:
11-
// else if target.contains("windows-gnu") {
12-
// println!("cargo:rustc-link-arg=-Wl,--subsystem,windows");
13-
// }
1410
}

src/controller.rs

Lines changed: 53 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ use crate::packets::p767::{c2s, s2c};
1212
// Идентификаторы клиентов
1313
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1414
pub enum ClientId {
15-
C,
16-
L,
15+
Cheat,
16+
Legit,
1717
}
1818

1919
// События для регулятора
@@ -22,7 +22,6 @@ pub enum Event {
2222
ClientData(ClientId, RawPacket),
2323
ClientDisconnected(ClientId),
2424
ServerData(RawPacket),
25-
// SwitchActive,
2625
}
2726

2827
// Регулятор
@@ -33,7 +32,8 @@ pub struct Controller {
3332
remote_tx: Sender<RawPacket>,
3433
event_rx: Receiver<Event>,
3534
threshold: Option<i32>,
36-
both_active: bool,
35+
cheat_active: bool,
36+
legit_active: bool,
3737
position: s2c::Position,
3838
last_action: i16,
3939
need_sync: bool,
@@ -57,7 +57,8 @@ impl Controller {
5757
remote_tx,
5858
event_rx,
5959
threshold,
60-
both_active: true,
60+
cheat_active: true,
61+
legit_active: true,
6162
position: s2c::Position {
6263
x: 0.0,
6364
y: 0.0,
@@ -77,42 +78,38 @@ impl Controller {
7778
match event {
7879
Event::ClientData(client_id, packet) => {
7980
if client_id == self.active_client {
80-
if self.both_active {
81+
if self.both_active() {
8182
if let Ok(Some(packet)) = packet.try_uncompress(self.threshold) {
8283
match packet.packet_id.0 {
8384
0x12 | 0x13 | 0x14 => {
8485
let _ = self.update_position(&packet);
8586
// Уведомляем пассивного клиента
8687
let passive = match self.active_client {
87-
ClientId::C => ClientId::L,
88-
ClientId::L => ClientId::C,
88+
ClientId::Cheat => ClientId::Legit,
89+
ClientId::Legit => ClientId::Cheat,
8990
};
9091

91-
let notice = match self.threshold {
92-
Some(t) => self
93-
.position
94-
.as_uncompressed()
95-
.unwrap()
96-
.compress(t as usize)
97-
.unwrap()
98-
.to_raw_packet(),
99-
None => self
100-
.position
101-
.as_uncompressed()
102-
.unwrap()
103-
.to_raw_packet()
104-
.unwrap(),
105-
};
92+
let notice = self
93+
.position
94+
.as_uncompressed()
95+
.unwrap()
96+
.compress_to_raw(self.threshold)
97+
.unwrap();
10698
match passive {
107-
ClientId::C => self.cheat_tx.send(notice).await.ok(),
108-
ClientId::L => self.legit_tx.send(notice).await.ok(),
99+
ClientId::Cheat => {
100+
self.cheat_tx.send(notice).await.ok()
101+
}
102+
ClientId::Legit => {
103+
self.legit_tx.send(notice).await.ok()
104+
}
109105
};
110106
}
111107

112108
_ => {}
113109
}
114110
}
115111
}
112+
116113
if self.bypass {
117114
if let Ok(Some(packet)) = packet.try_uncompress(self.threshold) {
118115
if packet.packet_id.0 == 0x07 {
@@ -135,19 +132,11 @@ impl Controller {
135132
println!("Синхронизация: Отправка {}", i);
136133
let mut new_transaction = t.clone();
137134
new_transaction.action = i;
138-
let new_transaction = match self.threshold {
139-
Some(t) => new_transaction
140-
.as_uncompressed()
141-
.unwrap()
142-
.compress(t as usize)
143-
.unwrap()
144-
.to_raw_packet(),
145-
None => new_transaction
146-
.as_uncompressed()
147-
.unwrap()
148-
.to_raw_packet()
149-
.unwrap(),
150-
};
135+
let new_transaction = new_transaction
136+
.as_uncompressed()
137+
.unwrap()
138+
.compress_to_raw(self.threshold)
139+
.unwrap();
151140
self.remote_tx
152141
.send(new_transaction)
153142
.await
@@ -164,44 +153,44 @@ impl Controller {
164153
}
165154
}
166155
}
167-
// Перенаправляем активного клиента на сервер
156+
168157
if let Err(e) = self.remote_tx.send(packet).await {
169-
eprintln!("Server send error: {}", e);
158+
println!("Ошибка отправки пакета на сервер: {}", e);
159+
return;
170160
}
171161
}
172162
}
173163
Event::ClientDisconnected(client_id) => {
174-
if !self.both_active {
164+
if !self.both_active() {
175165
println!("Оба клиента отключились");
176166
return;
177167
}
178-
self.both_active = false;
168+
match client_id {
169+
ClientId::Cheat => self.cheat_active = false,
170+
ClientId::Legit => self.legit_active = false,
171+
};
172+
179173
if self.active_client == client_id {
180-
// Автоматическое переключение при отключении активного
181174
self.active_client = match client_id {
182-
ClientId::C => ClientId::L,
183-
ClientId::L => ClientId::C,
175+
ClientId::Cheat => ClientId::Legit,
176+
ClientId::Legit => ClientId::Cheat,
184177
};
185178
println!("Переключился на {:?}", self.active_client);
186179
self.need_sync = true;
187180
}
188181
}
189182
Event::ServerData(packet) => {
190-
// Рассылаем всем клиентам
191-
self.cheat_tx.send(packet.clone()).await.ok();
192-
self.legit_tx.send(packet).await.ok();
193-
} // Event::SwitchActive => {
194-
// if self.can_switch {
195-
// self.active_client = match self.active_client {
196-
// ClientId::C => ClientId::L,
197-
// ClientId::L => ClientId::C,
198-
// };
199-
// println!(
200-
// "Manually switched active client to {:?}",
201-
// self.active_client
202-
// );
203-
// }
204-
// }
183+
if self.cheat_active {
184+
if self.cheat_tx.send(packet.clone()).await.is_err() {
185+
self.cheat_active = false;
186+
}
187+
}
188+
if self.legit_active {
189+
if self.legit_tx.send(packet).await.is_err() {
190+
self.legit_active = false;
191+
}
192+
}
193+
}
205194
}
206195
}
207196
}
@@ -233,6 +222,10 @@ impl Controller {
233222

234223
Ok(())
235224
}
225+
226+
fn both_active(&self) -> bool {
227+
(self.cheat_active == self.legit_active) && self.cheat_active
228+
}
236229
}
237230

238231
// Запуск клиентского обработчика
@@ -249,7 +242,6 @@ pub async fn run_client(
249242
loop {
250243
match RawPacket::read(&mut client_read).await {
251244
Ok(packet) => {
252-
if client_id == ClientId::C {}
253245
if event_tx
254246
.send(Event::ClientData(client_id, packet))
255247
.await

src/main.rs

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -33,11 +33,21 @@ mod updater;
3333

3434
#[tokio::main]
3535
async fn main() {
36+
if let Err(e) = run().await {
37+
println!("Ошибка: {}", e);
38+
} else {
39+
println!("Завершение работы?");
40+
}
41+
let _ = dialoguer::Confirm::new().interact();
42+
}
43+
44+
async fn run() -> anyhow::Result<()> {
3645
#[cfg(target_os = "windows")]
46+
#[cfg(not(debug_assertions))]
3747
unsafe {
3848
use windows::Win32::System::Console::AllocConsole;
3949

40-
AllocConsole().unwrap(); // создаёт новое окно консоли (conhost.exe)
50+
AllocConsole()?;
4151
}
4252

4353
println!(
@@ -71,7 +81,7 @@ __ __ _ ____
7181
.arg(&new_version.link)
7282
.output();
7383
loop {
74-
let _: String = dialoguer::Input::new().interact_text().unwrap();
84+
let _: String = dialoguer::Input::new().interact_text()?;
7585
}
7686
}
7787
Ok(None) => {
@@ -92,15 +102,14 @@ __ __ _ ____
92102
let (tx, rx) = mpsc::channel();
93103

94104
std::thread::spawn(|| unsafe { setup_keybind(tx) });
95-
println!("{}", rx.recv().unwrap());
105+
println!("{}", rx.recv()?);
96106
}
97107

98108
let (remote_addr, remote_dns) = {
99109
loop {
100110
let input: String = dialoguer::Input::with_theme(&ColorfulTheme::default())
101111
.with_prompt("Введите адрес сервера")
102-
.interact_text()
103-
.unwrap();
112+
.interact_text()?;
104113

105114
if let Some(addr) = resolve_host_port(&input, 25565, "minecraft", "tcp").await {
106115
break (addr, input);
@@ -132,7 +141,7 @@ __ __ _ ____
132141
Err(e) => {
133142
println!("Ошибка при создании сокета. {}", e);
134143
loop {
135-
let _: String = dialoguer::Input::new().interact_text().unwrap();
144+
let _: String = dialoguer::Input::new().interact_text()?;
136145
}
137146
}
138147
};
@@ -151,12 +160,9 @@ __ __ _ ____
151160
}
152161
});
153162

154-
if let Err(e) = handler.await.unwrap() {
155-
println!("Ошибка: {}", e);
156-
loop {
157-
let _: String = dialoguer::Input::new().interact_text().unwrap();
158-
}
159-
}
163+
handler.await??;
164+
165+
Ok(())
160166
}
161167

162168
async fn handle_connection(
@@ -315,10 +321,7 @@ async fn handle_clients(
315321
return Err(anyhow!("Licensed"));
316322
}
317323
2 => {
318-
let packet = match threshold {
319-
Some(t) => packet.compress(t as usize)?.to_raw_packet(),
320-
None => packet.to_raw_packet()?,
321-
};
324+
let packet = packet.compress_to_raw(threshold)?;
322325
packet.write(&mut cheat_stream).await?;
323326
packet.write(&mut legit_stream).await?;
324327
println!("[+] Login success");
@@ -363,7 +366,7 @@ async fn handle_clients(
363366
println!("[+] BYPASS Синхронизации")
364367
}
365368
let controller = Controller::new(
366-
ClientId::C,
369+
ClientId::Cheat,
367370
cheat_tx,
368371
legit_tx,
369372
remote_tx,
@@ -375,15 +378,15 @@ async fn handle_clients(
375378
tokio::spawn(run_client(
376379
cheat_read,
377380
cheat_write,
378-
ClientId::C,
381+
ClientId::Cheat,
379382
event_tx.clone(),
380383
cheat_rx,
381384
));
382385

383386
tokio::spawn(run_client(
384387
legit_read,
385388
legit_write,
386-
ClientId::L,
389+
ClientId::Legit,
387390
event_tx.clone(),
388391
legit_rx,
389392
));

0 commit comments

Comments
 (0)