core engine rewrite and client side changes

This commit is contained in:
2026-03-21 22:24:21 +07:00
parent af5ab22712
commit 46e8b4ae73
13 changed files with 573 additions and 376 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
use crate::connections::ip_store::FakeIpStore; use crate::connections::ip_store::FakeIpStore;
use hickory_proto::op::{Message, MessageType, ResponseCode}; use hickory_proto::op::{Message, MessageType, ResponseCode};
use hickory_proto::rr::{RData, Record, RecordType}; use hickory_proto::rr::{RData, Record, RecordType};
use netrunner_logger::{error, info}; use netrunner_logger::{debug, error, info};
use std::collections::HashSet; use std::collections::HashSet;
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
use tokio::fs::{self, File}; use tokio::fs::{self, File};
@@ -114,7 +114,7 @@ impl DnsHandler {
if self.forbidden_suffixes.iter().any(|s| name.ends_with(s)) if self.forbidden_suffixes.iter().any(|s| name.ends_with(s))
|| self.block_list.contains(&name) || self.block_list.contains(&name)
{ {
info!(domain = %name, "DNS: Blocked"); debug!(domain = %name, "DNS: Blocked");
res.set_response_code(ResponseCode::NXDomain); res.set_response_code(ResponseCode::NXDomain);
return res.to_vec().ok(); return res.to_vec().ok();
} }
+1 -1
View File
@@ -30,7 +30,7 @@ impl FakeIpStore {
self.next_ip += 1; self.next_ip += 1;
self.cache.put(host.to_string(), ip); self.cache.put(host.to_string(), ip);
self.rev_cache.put(ip, host.to_string()); self.rev_cache.put(ip, host.to_string());
info!(host = %host, ip = %ip, "Assigned new fake IP"); debug!(host = %host, ip = %ip, "Assigned new fake IP");
ip ip
} }
+1 -1
View File
@@ -3,4 +3,4 @@ pub mod ip_store;
pub mod tcp_connection; pub mod tcp_connection;
pub mod udp_connection; pub mod udp_connection;
pub const CHANNEL_CAPACITY: usize = 2048; pub const CHANNEL_CAPACITY: usize = 16;
+33 -115
View File
@@ -1,16 +1,9 @@
use std::time::Duration; use bytes::{Buf, Bytes, BytesMut};
use netrunner_core::proxy::connection::TCP_BUF_SIZE;
use bytes::Bytes;
use netrunner_core::protocol::codec::frame::FrameType;
use netrunner_core::protocol::codec::socks::TargetAddress;
use netrunner_core::proxy::connection::BUF_SIZE;
use netrunner_core::proxy::connection::muxer::{MuxMessage, Muxer};
use smoltcp::iface::SocketHandle; use smoltcp::iface::SocketHandle;
use smoltcp::socket::tcp; use smoltcp::socket::tcp;
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot};
use crate::connections::CHANNEL_CAPACITY;
pub enum ConnectionState { pub enum ConnectionState {
Established, Established,
Handshaking, Handshaking,
@@ -19,118 +12,44 @@ pub enum ConnectionState {
} }
pub struct TcpConnection { pub struct TcpConnection {
handle: SocketHandle, pub handle: SocketHandle,
state: ConnectionState, state: ConnectionState,
// UPLOAD: Ограниченный канал (Bounded) для Backpressure (128) // UPLOAD: Ограниченный канал для передачи данных наружу
tx: mpsc::Sender<Vec<u8>>, tx: mpsc::Sender<Bytes>,
// DOWNLOAD: Безлимитный канал (Unbounded), чтобы Муксер НИКОГДА не зависал // DOWNLOAD: Канал для приема данных из сети
rx: mpsc::UnboundedReceiver<Vec<u8>>, rx: mpsc::Receiver<Bytes>,
pending_data: Vec<u8>, pending_data: BytesMut,
handshake_rx: Option<oneshot::Receiver<()>>, handshake_rx: Option<oneshot::Receiver<()>>,
} }
const MAX_PENDING: usize = 4 * 1024 * 1024; const MAX_PENDING: usize = 32 * 512 * 1024;
const TCP_CHUNK_SIZE: usize = 65536;
impl TcpConnection { impl TcpConnection {
pub fn new(handle: SocketHandle, target_addr: TargetAddress, muxer: Muxer) -> Self { pub fn new(
// UPLOAD: Ограничиваем очередь handle: SocketHandle,
let (tx_to_mux, mut rx_from_smol) = mpsc::channel::<Vec<u8>>(CHANNEL_CAPACITY); ) -> (
Self,
// DOWNLOAD: Безлимитный канал до синхронного tick() mpsc::Receiver<Bytes>,
let (tx_to_smol, rx_from_proxy) = mpsc::unbounded_channel::<Vec<u8>>(); mpsc::Sender<Bytes>,
oneshot::Sender<()>,
) {
let (tx_to_net, rx_from_smol) = mpsc::channel::<Bytes>(TCP_BUF_SIZE);
let (tx_to_smol, rx_from_net) = mpsc::channel::<Bytes>(TCP_BUF_SIZE);
let (handshake_tx, handshake_rx) = oneshot::channel(); let (handshake_tx, handshake_rx) = oneshot::channel();
let stream_id = muxer.next_id(); let conn = Self {
tokio::spawn(async move {
// ИСПРАВЛЕНИЕ: Даем Муксеру ограниченный канал, как он и просит (тип mpsc::Sender)
// Делаем его достаточно вместительным (1024)
let (v_tx, mut v_rx) = mpsc::channel::<Bytes>(BUF_SIZE);
muxer.register_stream(stream_id, v_tx);
let connect_payload = target_addr.to_string();
if muxer
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::Connect,
data: Bytes::from(connect_payload),
})
.await
.is_err()
{
muxer.remove_stream(stream_id);
return;
}
let first_payload = tokio::time::timeout(Duration::from_secs(10), v_rx.recv()).await;
match first_payload {
Ok(Some(data)) => {
if data.len() >= 2 && data[1] == 0x00 {
let _ = handshake_tx.send(());
} else {
netrunner_logger::warn!(stream_id, "Server rejected TCP connection");
muxer.remove_stream(stream_id);
return;
}
}
_ => {
netrunner_logger::error!(stream_id, "Timeout waiting for proxy response");
muxer.remove_stream(stream_id);
return;
}
}
let to_proxy = async {
while let Some(data) = rx_from_smol.recv().await {
let msg = MuxMessage {
stream_id,
frame_type: FrameType::Data,
data: Bytes::from(data),
};
if muxer.send_to_netwrok(msg).await.is_err() {
break;
}
}
};
// МАГИЯ ЗДЕСЬ: Мы мгновенно читаем из ограниченного v_rx и переливаем
// в безлимитный tx_to_smol. send() у безлимитного канала никогда не блокируется.
// Поэтому v_rx всегда пустой, и Муксер никогда не зависнет!
let from_proxy = async {
while let Some(data) = v_rx.recv().await {
if data.is_empty() {
break;
}
if tx_to_smol.send(data.to_vec()).is_err() {
break;
}
}
};
tokio::select! {
_ = to_proxy => {}
_ = from_proxy => {}
}
let _ = muxer
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::Close,
data: Bytes::new(),
})
.await;
muxer.remove_stream(stream_id);
});
Self {
handle, handle,
state: ConnectionState::Handshaking, state: ConnectionState::Handshaking,
tx: tx_to_mux, tx: tx_to_net,
rx: rx_from_proxy, // Это UnboundedReceiver, здесь ничего менять не надо rx: rx_from_net,
pending_data: vec![], pending_data: BytesMut::new(),
handshake_rx: Some(handshake_rx), handshake_rx: Some(handshake_rx),
};
(conn, rx_from_smol, tx_to_smol, handshake_tx)
} }
}
pub fn tick(&mut self, socket: &mut tcp::Socket) -> bool { pub fn tick(&mut self, socket: &mut tcp::Socket) -> bool {
let state = socket.state(); let state = socket.state();
@@ -188,7 +107,7 @@ impl TcpConnection {
} }
fn poll_and_process(&mut self, socket: &mut tcp::Socket) { fn poll_and_process(&mut self, socket: &mut tcp::Socket) {
// 1. UPLOAD: Чанкинг и Backpressure (Защита от краша сервера) // 1. UPLOAD: Чанкинг и Backpressure
if socket.can_recv() { if socket.can_recv() {
while socket.can_recv() { while socket.can_recv() {
let mut channel_full = false; let mut channel_full = false;
@@ -199,10 +118,10 @@ impl TcpConnection {
return (0, ()); return (0, ());
} }
let chunk_size = std::cmp::min(data.len(), 16000); let chunk_size = std::cmp::min(data.len(), TCP_CHUNK_SIZE);
let chunk = &data[..chunk_size]; let chunk = &data[..chunk_size];
match self.tx.try_send(chunk.to_vec()) { match self.tx.try_send(Bytes::copy_from_slice(chunk)) {
Ok(_) => (chunk_size, ()), Ok(_) => (chunk_size, ()),
Err(mpsc::error::TrySendError::Full(_)) => { Err(mpsc::error::TrySendError::Full(_)) => {
channel_full = true; channel_full = true;
@@ -221,7 +140,7 @@ impl TcpConnection {
} }
} }
// 2. DOWNLOAD: Сброс безлимитного канала в буфер // 2. DOWNLOAD: Сброс ограниченного канала в буфер
while let Ok(data) = self.rx.try_recv() { while let Ok(data) = self.rx.try_recv() {
if self.pending_data.is_empty() && socket.can_send() { if self.pending_data.is_empty() && socket.can_send() {
match socket.send_slice(&data) { match socket.send_slice(&data) {
@@ -237,7 +156,6 @@ impl TcpConnection {
self.pending_data.extend_from_slice(&data); self.pending_data.extend_from_slice(&data);
} }
// Защита от OOM. 32MB более чем достаточно.
if self.pending_data.len() > MAX_PENDING { if self.pending_data.len() > MAX_PENDING {
netrunner_logger::error!( netrunner_logger::error!(
%self.handle, %self.handle,
@@ -254,7 +172,7 @@ impl TcpConnection {
if !self.pending_data.is_empty() && socket.can_send() { if !self.pending_data.is_empty() && socket.can_send() {
match socket.send_slice(&self.pending_data) { match socket.send_slice(&self.pending_data) {
Ok(n) => { Ok(n) => {
self.pending_data.drain(..n); self.pending_data.advance(n);
} }
Err(_) => {} Err(_) => {}
} }
+30 -85
View File
@@ -3,128 +3,71 @@ use smoltcp::socket::udp;
use smoltcp::wire::IpEndpoint; use smoltcp::wire::IpEndpoint;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use bytes::Bytes;
use netrunner_core::{
protocol::codec::{frame::FrameType, socks::TargetAddress},
proxy::connection::muxer::{MuxMessage, Muxer},
};
use crate::connections::CHANNEL_CAPACITY; use crate::connections::CHANNEL_CAPACITY;
use bytes::Bytes;
pub struct UdpConnection { pub struct UdpConnection {
pub handle: SocketHandle, pub handle: SocketHandle,
stream_id: u32, // UPLOAD: Ограниченный канал для передачи данных наружу
tx_to_net: mpsc::Sender<MuxMessage>, tx: mpsc::Sender<Bytes>,
rx_from_net: mpsc::UnboundedReceiver<Bytes>, // <-- ТУТ // DOWNLOAD: Канал для приема данных из сети
rx: mpsc::Receiver<Bytes>,
client_endpoint: Option<IpEndpoint>, client_endpoint: Option<IpEndpoint>,
last_activity: Instant, last_activity: Instant,
token: CancellationToken,
} }
const UDP_TIMEOUT: Duration = Duration::from_secs(60); const UDP_TIMEOUT: Duration = Duration::from_secs(60);
impl UdpConnection { impl UdpConnection {
pub fn new(handle: SocketHandle, target_addr: TargetAddress, muxer: Muxer) -> Self { /// Возвращает:
let stream_id = muxer.next_id(); /// 1. Экземпляр UdpConnection
let token = CancellationToken::new(); /// 2. Receiver (для чтения данных, отправляемых ИЗ smoltcp В сеть)
let task_token = token.clone(); /// 3. Sender (для записи данных ИЗ сети В smoltcp)
pub fn new(handle: SocketHandle) -> (Self, mpsc::Receiver<Bytes>, mpsc::Sender<Bytes>) {
let (tx_to_net, rx_from_smol) = mpsc::channel::<Bytes>(CHANNEL_CAPACITY);
let (tx_to_smol, rx_from_net) = mpsc::channel::<Bytes>(CHANNEL_CAPACITY);
let (tx_to_net, mut rx_from_smol) = mpsc::channel::<MuxMessage>(CHANNEL_CAPACITY); let conn = Self {
// ИСПРАВЛЕНИЕ: Внутренний безлимитный канал
let (internal_tx, internal_rx) = mpsc::unbounded_channel::<Bytes>();
let m_clone = muxer.clone();
tokio::spawn(async move {
// Даем Муксеру ограниченный канал (тип Sender), чтобы компилятор пропустил
let (v_tx, mut v_rx) = mpsc::channel::<Bytes>(1024);
m_clone.register_stream(stream_id, v_tx);
let _ = m_clone
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::UdpConnect,
data: Bytes::from(target_addr.to_string()),
})
.await;
let to_proxy = async {
while let Some(msg) = rx_from_smol.recv().await {
if m_clone.send_to_netwrok(msg).await.is_err() {
break;
}
}
};
// Мгновенно выкачиваем данные из Муксера в безлимитный внутренний канал
let from_proxy = async {
while let Some(data) = v_rx.recv().await {
if internal_tx.send(data).is_err() {
break;
}
}
};
tokio::select! {
_ = to_proxy => {}
_ = from_proxy => {} // Не забудь добавить этот блок в select!
_ = task_token.cancelled() => {}
}
let _ = m_clone
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::Close,
data: Bytes::new(),
})
.await;
m_clone.remove_stream(stream_id);
});
Self {
handle, handle,
stream_id, tx: tx_to_net,
tx_to_net, rx: rx_from_net,
rx_from_net: internal_rx, // Сохраняем безлимитный ресивер
client_endpoint: None, client_endpoint: None,
last_activity: Instant::now(), last_activity: Instant::now(),
token, };
}
(conn, rx_from_smol, tx_to_smol)
} }
pub fn tick(&mut self, socket: &mut udp::Socket) -> bool { pub fn tick(&mut self, socket: &mut udp::Socket) -> bool {
// Проверка таймаута бездействия
if self.last_activity.elapsed() > UDP_TIMEOUT { if self.last_activity.elapsed() > UDP_TIMEOUT {
netrunner_logger::debug!(%self.handle, "UDP Session closed due to timeout"); netrunner_logger::debug!(%self.handle, "UDP Session closed due to timeout");
self.token.cancel();
socket.close(); socket.close();
return false; return false;
} }
// 1. UPLOAD: Читаем из smoltcp и отправляем в виртуальный канал
if socket.can_recv() { if socket.can_recv() {
while let Ok((data, metadata)) = socket.recv() { while let Ok((data, metadata)) = socket.recv() {
self.client_endpoint = Some(metadata.endpoint); self.client_endpoint = Some(metadata.endpoint);
let msg = MuxMessage { // Копируем данные в Bytes и пытаемся протолкнуть.
stream_id: self.stream_id, // Если канал забит (Full), пакет дропается — это штатное поведение UDP.
frame_type: FrameType::UdpData, if self.tx.try_send(Bytes::copy_from_slice(data)).is_ok() {
data: Bytes::copy_from_slice(data),
};
if self.tx_to_net.try_send(msg).is_ok() {
self.last_activity = Instant::now(); self.last_activity = Instant::now();
} }
} }
} }
// 2. DOWNLOAD: Читаем из виртуального канала и пишем в smoltcp
if socket.can_send() { if socket.can_send() {
if let Some(endpoint) = self.client_endpoint { if let Some(endpoint) = self.client_endpoint {
while let Ok(data) = self.rx_from_net.try_recv() { while let Ok(data) = self.rx.try_recv() {
// Сигнал закрытия стрима
if data.is_empty() { if data.is_empty() {
self.token.cancel(); socket.close();
break; return false;
} }
match socket.send_slice(&data, endpoint) { match socket.send_slice(&data, endpoint) {
@@ -132,6 +75,8 @@ impl UdpConnection {
self.last_activity = Instant::now(); self.last_activity = Instant::now();
} }
Err(_) => { Err(_) => {
// Если сокет smoltcp переполнен, прерываем цикл.
// Пакет теряется, что опять же является нормой для UDP.
break; break;
} }
} }
+159 -7
View File
@@ -1,16 +1,25 @@
use netrunner_core::{protocol::codec::socks::TargetAddress, proxy::connection::muxer::Muxer}; use bytes::Bytes;
use netrunner_core::{
protocol::codec::{frame::FrameType, socks::TargetAddress},
proxy::connection::{
TCP_BUF_SIZE,
muxer::{MuxMessage, Muxer},
},
};
use netrunner_logger::{debug, info, warn}; use netrunner_logger::{debug, info, warn};
use smoltcp::{ use smoltcp::{
iface::{SocketHandle, SocketSet}, iface::{SocketHandle, SocketSet},
socket::{AnySocket, icmp, tcp, udp}, socket::{AnySocket, icmp, tcp, udp},
wire::{IpListenEndpoint, IpProtocol, Ipv4Packet, TcpPacket, UdpPacket}, wire::{IpListenEndpoint, IpProtocol, Ipv4Packet, TcpPacket, UdpPacket},
}; };
use std::{collections::HashMap, time::Instant as StdInstant}; use std::{collections::HashMap, time::Duration, time::Instant as StdInstant};
use tokio::sync::mpsc;
use crate::connections::{ use crate::connections::{
dns::DnsHandler, ip_store::FakeIpStore, tcp_connection::TcpConnection, CHANNEL_CAPACITY, dns::DnsHandler, ip_store::FakeIpStore, tcp_connection::TcpConnection,
udp_connection::UdpConnection, udp_connection::UdpConnection,
}; };
pub struct ConnectionManager { pub struct ConnectionManager {
last_activity: HashMap<SocketHandle, StdInstant>, last_activity: HashMap<SocketHandle, StdInstant>,
active_tcp_sessions: HashMap<SocketHandle, TcpConnection>, active_tcp_sessions: HashMap<SocketHandle, TcpConnection>,
@@ -35,6 +44,7 @@ impl ConnectionManager {
muxer, muxer,
} }
} }
pub fn start_listening(&mut self, socket_set: &mut SocketSet) { pub fn start_listening(&mut self, socket_set: &mut SocketSet) {
for (_, socket) in socket_set.iter_mut() { for (_, socket) in socket_set.iter_mut() {
if let Some(tcp) = tcp::Socket::downcast_mut(socket) { if let Some(tcp) = tcp::Socket::downcast_mut(socket) {
@@ -65,7 +75,6 @@ impl ConnectionManager {
Some(ep) => ep, Some(ep) => ep,
None => { None => {
warn!(handle=?socket, "Attempted to resolve target for an unconnected socket"); warn!(handle=?socket, "Attempted to resolve target for an unconnected socket");
return TargetAddress::Domain("disconnected".to_string(), 0); return TargetAddress::Domain("disconnected".to_string(), 0);
} }
}; };
@@ -96,6 +105,7 @@ impl ConnectionManager {
} }
} }
} }
pub fn process_sockets(&mut self, socket_set: &mut SocketSet) { pub fn process_sockets(&mut self, socket_set: &mut SocketSet) {
for (handle, socket) in socket_set.iter_mut() { for (handle, socket) in socket_set.iter_mut() {
if let Some(tcp) = tcp::Socket::downcast_mut(socket) { if let Some(tcp) = tcp::Socket::downcast_mut(socket) {
@@ -134,8 +144,90 @@ impl ConnectionManager {
} }
info!(%handle, "New TCP session established for target: {:?}", target); info!(%handle, "New TCP session established for target: {:?}", target);
let conn = TcpConnection::new(handle, target, self.muxer.clone());
// 1. Создаем соединение и получаем каналы
let (conn, mut rx_from_smol, tx_to_smol, handshake_tx) = TcpConnection::new(handle);
self.active_tcp_sessions.insert(handle, conn); self.active_tcp_sessions.insert(handle, conn);
// 2. Выносим логику мультиплексирования в фоновую задачу
let muxer = self.muxer.clone();
let stream_id = muxer.next_id();
let connect_payload = target.to_string();
tokio::spawn(async move {
let (v_tx, mut v_rx) = mpsc::channel::<Bytes>(TCP_BUF_SIZE);
muxer.register_stream(stream_id, v_tx);
if muxer
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::Connect,
data: Bytes::from(connect_payload),
})
.await
.is_err()
{
muxer.remove_stream(stream_id);
return;
}
let first_payload =
tokio::time::timeout(Duration::from_secs(10), v_rx.recv()).await;
match first_payload {
Ok(Some(data)) => {
if data.len() >= 2 && data[1] == 0x00 {
let _ = handshake_tx.send(());
} else {
netrunner_logger::warn!(stream_id, "Server rejected TCP connection");
muxer.remove_stream(stream_id);
return;
}
}
_ => {
netrunner_logger::error!(stream_id, "Timeout waiting for proxy response");
muxer.remove_stream(stream_id);
return;
}
}
let to_proxy = async {
while let Some(data) = rx_from_smol.recv().await {
let msg = MuxMessage {
stream_id,
frame_type: FrameType::Data,
data,
};
if muxer.send_to_netwrok(msg).await.is_err() {
break;
}
}
};
let from_proxy = async {
while let Some(data) = v_rx.recv().await {
if data.is_empty() {
break;
}
if tx_to_smol.send(data).await.is_err() {
break;
}
}
};
tokio::select! {
_ = to_proxy => {}
_ = from_proxy => {}
}
let _ = muxer
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::Close,
data: Bytes::new(),
})
.await;
muxer.remove_stream(stream_id);
});
} }
if let Some(conn) = self.active_tcp_sessions.get_mut(&handle) { if let Some(conn) = self.active_tcp_sessions.get_mut(&handle) {
@@ -149,6 +241,7 @@ impl ConnectionManager {
socket.close(); socket.close();
} }
} }
fn handle_udp(&mut self, handle: SocketHandle, socket: &mut udp::Socket) { fn handle_udp(&mut self, handle: SocketHandle, socket: &mut udp::Socket) {
self.last_activity.insert(handle, StdInstant::now()); self.last_activity.insert(handle, StdInstant::now());
@@ -187,8 +280,65 @@ impl ConnectionManager {
netrunner_logger::info!(%handle, target = %target, "New UDP proxied session established"); netrunner_logger::info!(%handle, target = %target, "New UDP proxied session established");
let conn = UdpConnection::new(handle, target, self.muxer.clone()); // 1. Создаем UDP соединение и получаем каналы
let (conn, mut rx_from_smol, tx_to_smol) = UdpConnection::new(handle);
self.active_udp_sessions.insert(handle, conn); self.active_udp_sessions.insert(handle, conn);
// 2. Фоновая задача для Muxer'а
let muxer = self.muxer.clone();
let stream_id = muxer.next_id();
let connect_payload = target.to_string();
tokio::spawn(async move {
let (v_tx, mut v_rx) = mpsc::channel::<Bytes>(CHANNEL_CAPACITY);
muxer.register_stream(stream_id, v_tx);
let _ = muxer
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::UdpConnect,
data: Bytes::from(connect_payload),
})
.await;
let to_proxy = async {
while let Some(data) = rx_from_smol.recv().await {
let msg = MuxMessage {
stream_id,
frame_type: FrameType::UdpData,
data,
};
if muxer.send_to_netwrok(msg).await.is_err() {
break;
}
}
};
let from_proxy = async {
while let Some(data) = v_rx.recv().await {
if data.is_empty() {
break;
}
if tx_to_smol.send(data).await.is_err() {
break;
}
}
};
tokio::select! {
_ = to_proxy => {}
_ = from_proxy => {}
}
let _ = muxer
.send_to_netwrok(MuxMessage {
stream_id,
frame_type: FrameType::Close,
data: Bytes::new(),
})
.await;
muxer.remove_stream(stream_id);
});
} }
if let Some(conn) = self.active_udp_sessions.get_mut(&handle) { if let Some(conn) = self.active_udp_sessions.get_mut(&handle) {
@@ -223,11 +373,11 @@ impl ConnectionManager {
tcp::SocketBuffer::new(vec![0; buf_size]), tcp::SocketBuffer::new(vec![0; buf_size]),
); );
// Nagle отключен - это правильно для уменьшения задержек
socket.set_nagle_enabled(false); socket.set_nagle_enabled(false);
socket.set_ack_delay(None); socket.set_ack_delay(None);
socket socket
} }
pub fn try_create_socket_from_packet(&mut self, packet: &[u8], socket_set: &mut SocketSet) { pub fn try_create_socket_from_packet(&mut self, packet: &[u8], socket_set: &mut SocketSet) {
let Ok(ip_packet) = Ipv4Packet::new_checked(packet) else { let Ok(ip_packet) = Ipv4Packet::new_checked(packet) else {
return; return;
@@ -357,6 +507,7 @@ impl ConnectionManager {
self.failed_until.remove(&handle); self.failed_until.remove(&handle);
} }
} }
pub fn setup_sockets(n_icmp: usize) -> SocketSet<'static> { pub fn setup_sockets(n_icmp: usize) -> SocketSet<'static> {
let mut sockets = SocketSet::new(Vec::with_capacity(48)); let mut sockets = SocketSet::new(Vec::with_capacity(48));
@@ -366,6 +517,7 @@ impl ConnectionManager {
sockets sockets
} }
pub fn log_status(&self, socket_set: &SocketSet) { pub fn log_status(&self, socket_set: &SocketSet) {
let mut established = 0; let mut established = 0;
let mut total_tcp = 0; let mut total_tcp = 0;
+107
View File
@@ -6,9 +6,11 @@ use std::{
Arc, LazyLock, Mutex, Arc, LazyLock, Mutex,
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
}, },
time::Instant as StdInstant, // Добавлено для расчёта скорости
}; };
use bytes::BytesMut; use bytes::BytesMut;
use netrunner_logger::info; // Предполагается, что у тебя есть этот логгер
use smoltcp::{ use smoltcp::{
phy::{self, Device, DeviceCapabilities}, phy::{self, Device, DeviceCapabilities},
time::Instant, time::Instant,
@@ -18,6 +20,17 @@ use tokio::sync::mpsc;
const TOKEN_BUFFER_LIST_MAX_SIZE: usize = 64; const TOKEN_BUFFER_LIST_MAX_SIZE: usize = 64;
static TOKEN_BUFFER_LIST: LazyLock<Mutex<Vec<BytesMut>>> = LazyLock::new(|| Mutex::new(Vec::new())); static TOKEN_BUFFER_LIST: LazyLock<Mutex<Vec<BytesMut>>> = LazyLock::new(|| Mutex::new(Vec::new()));
// Структура, которую мы будем возвращать пользователю
#[derive(Debug, Clone, Copy)]
pub struct TrafficStats {
pub rx_bytes: u64,
pub tx_bytes: u64,
pub rx_packets: u64,
pub tx_packets: u64,
pub rx_speed_mb_s: f64,
pub tx_speed_mb_s: f64,
}
pub struct TokenBuffer { pub struct TokenBuffer {
buffer: BytesMut, buffer: BytesMut,
} }
@@ -65,6 +78,22 @@ pub struct VirtTunDevice {
rx_queue: mpsc::UnboundedReceiver<TokenBuffer>, rx_queue: mpsc::UnboundedReceiver<TokenBuffer>,
tx_queue: mpsc::UnboundedSender<TokenBuffer>, tx_queue: mpsc::UnboundedSender<TokenBuffer>,
rx_avail: Arc<AtomicBool>, rx_avail: Arc<AtomicBool>,
// === Статистика трафика ===
rx_bytes: u64,
tx_bytes: u64,
rx_packets: u64,
tx_packets: u64,
// Внутренние переменные для расчёта скорости
last_speed_calc: StdInstant,
last_rx_bytes: u64,
last_tx_bytes: u64,
cached_rx_speed: f64,
cached_tx_speed: f64,
// Для периодического логирования
last_log_time: StdInstant,
} }
impl VirtTunDevice { impl VirtTunDevice {
@@ -80,11 +109,26 @@ impl VirtTunDevice {
let (from_smoltcp_tx, from_smoltcp_rx) = mpsc::unbounded_channel(); let (from_smoltcp_tx, from_smoltcp_rx) = mpsc::unbounded_channel();
let rx_avail = Arc::new(AtomicBool::new(false)); let rx_avail = Arc::new(AtomicBool::new(false));
let now = StdInstant::now();
let device = Self { let device = Self {
capabilities, capabilities,
rx_queue: to_smoltcp_rx, rx_queue: to_smoltcp_rx,
tx_queue: from_smoltcp_tx, tx_queue: from_smoltcp_tx,
rx_avail: rx_avail.clone(), rx_avail: rx_avail.clone(),
rx_bytes: 0,
tx_bytes: 0,
rx_packets: 0,
tx_packets: 0,
last_speed_calc: now,
last_rx_bytes: 0,
last_tx_bytes: 0,
cached_rx_speed: 0.0,
cached_tx_speed: 0.0,
last_log_time: now,
}; };
(device, to_smoltcp_tx, from_smoltcp_rx, rx_avail) (device, to_smoltcp_tx, from_smoltcp_rx, rx_avail)
@@ -94,6 +138,54 @@ impl VirtTunDevice {
pub fn mark_rx_available(&self) { pub fn mark_rx_available(&self) {
self.rx_avail.store(true, Ordering::Release); self.rx_avail.store(true, Ordering::Release);
} }
pub fn get_stats(&mut self) -> TrafficStats {
let now = StdInstant::now();
let elapsed_speed = now.duration_since(self.last_speed_calc).as_secs_f64();
if elapsed_speed >= 1.0 {
let rx_diff = self.rx_bytes.saturating_sub(self.last_rx_bytes);
let tx_diff = self.tx_bytes.saturating_sub(self.last_tx_bytes);
// Переводим в МегаБайты в секунду (MB/s)
self.cached_rx_speed = (rx_diff as f64 / 1_048_576.0) / elapsed_speed;
self.cached_tx_speed = (tx_diff as f64 / 1_048_576.0) / elapsed_speed;
self.last_rx_bytes = self.rx_bytes;
self.last_tx_bytes = self.tx_bytes;
self.last_speed_calc = now;
}
TrafficStats {
rx_bytes: self.rx_bytes,
tx_bytes: self.tx_bytes,
rx_packets: self.rx_packets,
tx_packets: self.tx_packets,
rx_speed_mb_s: self.cached_rx_speed,
tx_speed_mb_s: self.cached_tx_speed,
}
}
/// Внутренний метод проверки таймера для вывода логов
fn check_and_log_stats(&mut self) {
let now = StdInstant::now();
// Логируем каждые 5 секунд
if now.duration_since(self.last_log_time).as_secs() >= 5 {
let stats = self.get_stats(); // Заодно обновляем скорости
info!(
"TunDevice Traffic: RX: {:.2} MB ({} pkts) | TX: {:.2} MB ({} pkts) | Speed: ↓{:.2} MB/s, ↑{:.2} MB/s",
stats.rx_bytes as f64 / 1_048_576.0,
stats.rx_packets,
stats.tx_bytes as f64 / 1_048_576.0,
stats.tx_packets,
stats.rx_speed_mb_s,
stats.tx_speed_mb_s
);
self.last_log_time = now;
}
}
} }
impl Device for VirtTunDevice { impl Device for VirtTunDevice {
@@ -101,7 +193,15 @@ impl Device for VirtTunDevice {
type TxToken<'a> = VirtTxToken<'a>; type TxToken<'a> = VirtTxToken<'a>;
fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
// Проверяем, не пора ли записать стату в лог. receive() вызывается очень часто,
// поэтому это отличное место для heartbeat таймера.
self.check_and_log_stats();
if let Ok(buffer) = self.rx_queue.try_recv() { if let Ok(buffer) = self.rx_queue.try_recv() {
// Учет входящего трафика (DOWNLOAD)
self.rx_bytes += buffer.len() as u64;
self.rx_packets += 1;
let rx = Self::RxToken { let rx = Self::RxToken {
buffer, buffer,
phantom_device: PhantomData, phantom_device: PhantomData,
@@ -147,8 +247,15 @@ impl phy::TxToken for VirtTxToken<'_> {
unsafe { unsafe {
buffer.set_len(len); buffer.set_len(len);
} }
let result = f(&mut buffer); let result = f(&mut buffer);
// Учет исходящего трафика (UPLOAD)
self.0.tx_bytes += len as u64;
self.0.tx_packets += 1;
let _ = self.0.tx_queue.send(buffer); let _ = self.0.tx_queue.send(buffer);
result result
} }
} }
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::protocol::codec::frame::FrameType; use crate::protocol::codec::frame::FrameType;
use crate::proxy::connection::muxer::{MuxMessage, Muxer}; use crate::proxy::connection::muxer::{MuxMessage, Muxer};
use crate::proxy::connection::BUF_SIZE; use crate::proxy::connection::{TCP_BUF_SIZE, UDP_BUF_SIZE};
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use netrunner_logger::{debug, error}; use netrunner_logger::{debug, error};
use tokio::net::UdpSocket; use tokio::net::UdpSocket;
@@ -16,7 +16,7 @@ pub async fn run_proxy_bridge<R, W>(
R: tokio::io::AsyncReadExt + Unpin, R: tokio::io::AsyncReadExt + Unpin,
W: tokio::io::AsyncWriteExt + Unpin, W: tokio::io::AsyncWriteExt + Unpin,
{ {
let mut buf = BytesMut::with_capacity(BUF_SIZE); let mut buf = BytesMut::with_capacity(TCP_BUF_SIZE);
loop { loop {
tokio::select! { tokio::select! {
@@ -81,7 +81,7 @@ pub async fn run_udp_bridge(
muxer: Muxer, muxer: Muxer,
mut v_rx: mpsc::Receiver<Bytes>, mut v_rx: mpsc::Receiver<Bytes>,
) { ) {
let mut buf = [0u8; 65536]; let mut buf = BytesMut::with_capacity(UDP_BUF_SIZE);
loop { loop {
tokio::select! { tokio::select! {
+27 -29
View File
@@ -13,7 +13,7 @@ use crate::{
engine::TunnelEngine, engine::TunnelEngine,
handler::StreamHandler, handler::StreamHandler,
muxer::{MuxMessage, Muxer}, muxer::{MuxMessage, Muxer},
BUF_SIZE, CHANNEL_SIZE, MESSAGE_CHANNEL_SIZE, TCP_BUF_SIZE,
}, },
tlseng::profile::BrowserProfile, tlseng::profile::BrowserProfile,
}; };
@@ -53,7 +53,7 @@ impl Connection {
Self { Self {
inbound, inbound,
outbound, outbound,
read_buf: BytesMut::with_capacity(BUF_SIZE), read_buf: BytesMut::with_capacity(TCP_BUF_SIZE),
codec: Codec::new(init), codec: Codec::new(init),
} }
} }
@@ -62,7 +62,7 @@ impl Connection {
Self { Self {
inbound, inbound,
outbound, outbound,
read_buf: BytesMut::with_capacity(BUF_SIZE), read_buf: BytesMut::with_capacity(TCP_BUF_SIZE),
codec: Codec::new(false), codec: Codec::new(false),
} }
} }
@@ -138,8 +138,11 @@ impl ClientHandler {
} }
} }
let (mux_tx, mux_rx) = mpsc::channel(CHANNEL_SIZE); // --- ИЗМЕНЕНИЕ ДЛЯ НОВОГО MUXER ---
let muxer = Muxer::new(mux_tx, true); let (control_tx, control_rx) = mpsc::channel(MESSAGE_CHANNEL_SIZE);
let (data_tx, data_rx) = mpsc::channel(MESSAGE_CHANNEL_SIZE);
let muxer = Muxer::new(control_tx, data_tx, true);
let handler = let handler =
std::sync::Arc::new(StreamHandler::new(muxer.clone(), ConnectionRole::Client)); std::sync::Arc::new(StreamHandler::new(muxer.clone(), ConnectionRole::Client));
@@ -149,7 +152,8 @@ impl ClientHandler {
outbound: conn.outbound, outbound: conn.outbound,
codec: conn.codec, codec: conn.codec,
read_buf: conn.read_buf, read_buf: conn.read_buf,
mux_rx, control_rx, // Передаем оба ресивера в Engine
data_rx, // Передаем оба ресивера в Engine
handler, handler,
token: token.clone(), token: token.clone(),
}; };
@@ -203,17 +207,17 @@ impl TunnelHandler for ClientHandler {
target, target,
} => { } => {
let stream_id = self.muxer.next_id(); let stream_id = self.muxer.next_id();
let (v_tx, mut v_rx) = mpsc::channel::<bytes::Bytes>(BUF_SIZE); let (v_tx, mut v_rx) = mpsc::channel::<bytes::Bytes>(TCP_BUF_SIZE);
self.muxer.register_stream(stream_id, v_tx); self.muxer.register_stream(stream_id, v_tx);
// Используем send_control для отправки FrameType::Connect
self.muxer self.muxer
.send_to_netwrok(MuxMessage { .send_control(
stream_id, stream_id,
frame_type: FrameType::Connect, FrameType::Connect,
data: bytes::Bytes::from(target.to_string()), bytes::Bytes::from(target.to_string()),
}) )
.await .await?;
.map_err(|e| e.to_string())?;
let first_payload = let first_payload =
tokio::time::timeout(std::time::Duration::from_secs(10), v_rx.recv()) tokio::time::timeout(std::time::Duration::from_secs(10), v_rx.recv())
@@ -251,6 +255,7 @@ impl TunnelHandler for ClientHandler {
} }
} }
} }
pub struct ServerHandler { pub struct ServerHandler {
pub conn: Connection, pub conn: Connection,
pub token: CancellationToken, pub token: CancellationToken,
@@ -258,8 +263,6 @@ pub struct ServerHandler {
impl ServerHandler { impl ServerHandler {
async fn handle_fallback(outbound: &mut OwnedWriteHalf) { async fn handle_fallback(outbound: &mut OwnedWriteHalf) {
// Формируем правдоподобный HTTP-ответ.
// Заголовок "Server: nginx" помогает мимикрировать под обычный веб-сервер.
let fallback_response = "HTTP/1.1 302 Found\r\n\ let fallback_response = "HTTP/1.1 302 Found\r\n\
Server: nginx/1.18.0 (Ubuntu)\r\n\ Server: nginx/1.18.0 (Ubuntu)\r\n\
Location: https://www.ubuntu.com/\r\n\ Location: https://www.ubuntu.com/\r\n\
@@ -267,11 +270,8 @@ impl ServerHandler {
Connection: close\r\n\ Connection: close\r\n\
\r\n"; \r\n";
// Пытаемся отправить ответ сканеру/цензору, игнорируя ошибки (если он уже отключился)
let _ = outbound.write_all(fallback_response.as_bytes()).await; let _ = outbound.write_all(fallback_response.as_bytes()).await;
let _ = outbound.flush().await; let _ = outbound.flush().await;
// Корректно закрываем соединение (отправляем FIN/RST)
let _ = outbound.shutdown().await; let _ = outbound.shutdown().await;
} }
} }
@@ -280,10 +280,12 @@ impl ServerHandler {
impl TunnelHandler for ServerHandler { impl TunnelHandler for ServerHandler {
async fn run(mut self) -> Result<(), String> { async fn run(mut self) -> Result<(), String> {
info!("Acting as TLS Server"); info!("Acting as TLS Server");
let (mux_tx, mux_rx) = mpsc::channel(CHANNEL_SIZE);
let muxer = Muxer::new(mux_tx, false);
// Тайм-аут для защиты от "сканеров-молчунов" (Active Probing) // --- ИЗМЕНЕНИЕ ДЛЯ НОВОГО MUXER ---
let (control_tx, control_rx) = mpsc::channel(MESSAGE_CHANNEL_SIZE);
let (data_tx, data_rx) = mpsc::channel(MESSAGE_CHANNEL_SIZE);
let muxer = Muxer::new(control_tx, data_tx, false);
let handshake_timeout = std::time::Duration::from_secs(5); let handshake_timeout = std::time::Duration::from_secs(5);
let hello = loop { let hello = loop {
@@ -294,7 +296,6 @@ impl TunnelHandler for ServerHandler {
{ {
Ok(b) => break b, Ok(b) => break b,
Err(e) if e.action == ErrorAction::Wait => { Err(e) if e.action == ErrorAction::Wait => {
// Используем timeout: если за 5 сек не пришел полный handshake - рвем/фолбечим
let read_res = tokio::time::timeout( let read_res = tokio::time::timeout(
handshake_timeout, handshake_timeout,
self.conn.inbound.read_buf(&mut self.conn.read_buf), self.conn.inbound.read_buf(&mut self.conn.read_buf),
@@ -306,35 +307,31 @@ impl TunnelHandler for ServerHandler {
return Err("Client closed connection before handshake".into()); return Err("Client closed connection before handshake".into());
} }
Ok(Ok(_)) => { Ok(Ok(_)) => {
// Прочитали кусок, идем на следующий круг проверять handshake
continue; continue;
} }
Ok(Err(e)) => { Ok(Err(e)) => {
return Err(format!("Socket read error: {}", e)); return Err(format!("Socket read error: {}", e));
} }
Err(_) => { Err(_) => {
// СРАБОТАЛ ТАЙМ-АУТ
netrunner_logger::warn!( netrunner_logger::warn!(
"Handshake timeout (Scanner detected). Triggering fallback." "Handshake timeout (Scanner detected). Triggering fallback."
); );
ServerHandler::handle_fallback(&mut self.conn.outbound).await; ServerHandler::handle_fallback(&mut self.conn.outbound).await;
return Ok(()); // Выходим без ошибки, чтобы не крашить сервер return Ok(());
} }
} }
} }
Err(e) => { Err(e) => {
// ПРИШЕЛ МУСОР ИЛИ НЕВЕРНЫЙ ФОРМАТ (HTTP сканер)
netrunner_logger::warn!( netrunner_logger::warn!(
error = ?e, error = ?e,
"Invalid handshake format (Scanner detected). Triggering fallback." "Invalid handshake format (Scanner detected). Triggering fallback."
); );
ServerHandler::handle_fallback(&mut self.conn.outbound).await; ServerHandler::handle_fallback(&mut self.conn.outbound).await;
return Ok(()); // Выходим без ошибки return Ok(());
} }
} }
}; };
// --- ЕСЛИ МЫ ЗДЕСЬ, ХЕНДШЕЙК ПРОШЕЛ УСПЕШНО ---
self.conn self.conn
.outbound .outbound
.write_all(&hello) .write_all(&hello)
@@ -348,7 +345,8 @@ impl TunnelHandler for ServerHandler {
outbound: self.conn.outbound, outbound: self.conn.outbound,
codec: self.conn.codec, codec: self.conn.codec,
read_buf: self.conn.read_buf, read_buf: self.conn.read_buf,
mux_rx, control_rx, // Передаем оба ресивера в Engine
data_rx, // Передаем оба ресивера в Engine
handler, handler,
token: self.token, token: self.token,
} }
+148 -78
View File
@@ -5,7 +5,7 @@ use netrunner_logger::{debug, error, info};
use tokio::{ use tokio::{
io::{AsyncReadExt, AsyncWriteExt}, io::{AsyncReadExt, AsyncWriteExt},
net::tcp::{OwnedReadHalf, OwnedWriteHalf}, net::tcp::{OwnedReadHalf, OwnedWriteHalf},
sync::mpsc::Receiver, sync::{mpsc::Receiver, Mutex},
}; };
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
@@ -22,99 +22,161 @@ pub struct TunnelEngine {
pub outbound: OwnedWriteHalf, pub outbound: OwnedWriteHalf,
pub codec: Codec, pub codec: Codec,
pub read_buf: BytesMut, pub read_buf: BytesMut,
pub mux_rx: Receiver<MuxMessage>, pub control_rx: Receiver<MuxMessage>,
pub data_rx: Receiver<MuxMessage>,
pub handler: Arc<StreamHandler>, pub handler: Arc<StreamHandler>,
pub token: CancellationToken, pub token: CancellationToken,
} }
impl TunnelEngine { impl TunnelEngine {
pub async fn run(self) -> Result<(), String> { pub async fn run(self) -> Result<(), String> {
let mut inbound = self.inbound; let inbound = self.inbound;
let mut outbound = self.outbound; let outbound = self.outbound;
let mut codec = self.codec;
let mut read_buf = self.read_buf;
let mut mux_rx = self.mux_rx;
let handler = self.handler;
// Оборачиваем кодек в потокобезопасный мьютекс
let codec = Arc::new(Mutex::new(self.codec));
let read_buf = self.read_buf;
let control_rx = self.control_rx;
let data_rx = self.data_rx;
let handler = self.handler;
let token = self.token; let token = self.token;
let mut heartbeat = tokio::time::interval(std::time::Duration::from_secs(15));
// Клонируем Arc для независимых тасок
let codec_reader = codec.clone();
let codec_writer = codec.clone();
let token_reader = token.clone();
let token_writer = token.clone();
// ==========================================
// 1. READER TASK (Только чтение и расшифровка)
// ==========================================
let reader_handle = tokio::spawn(async move {
let mut read_buf = read_buf;
let mut inbound = inbound;
loop { loop {
tokio::select! { tokio::select! {
_ = token.cancelled() => { _ = token_reader.cancelled() => {
info!("TunnelEngine: Shutdown signal received. Closing..."); info!("Reader Task: Shutdown signal received.");
return Ok(()); break;
}
res = inbound.read_buf(&mut read_buf) => {
let n = res.map_err(|e| e.to_string())?;
// --- ИСПРАВЛЕННАЯ ЛОГИКА EOF ---
if n == 0 {
if read_buf.is_empty() {
info!("Connection closed by peer (Clean EOF)");
} else {
error!("Connection abruptly closed by peer (Incomplete frame: {} bytes left)", read_buf.len());
}
// ВЫХОДИМ В ЛЮБОМ СЛУЧАЕ, СОКЕТ МЕРТВ!
return Err::<(), String>("EOF".into());
} }
res = Self::process_inbound(&mut inbound, &mut codec, &mut read_buf, &handler) => { // Вектор для фреймов. Мы расшифруем всё быстро,
res? // сложим сюда и отпустим лок Кодека.
let mut frames = Vec::new();
{
// Блокируем кодек только на время математики (расшифровки)
let mut c = codec_reader.lock().await;
loop {
match c.inbound(&mut read_buf) {
Ok(Some(frame)) => frames.push(frame),
Ok(None) => break,
Err(e) => {
if e.action == ErrorAction::Wait {
break;
}
if e.action == ErrorAction::Drop {
error!("CRITICAL: Crypto tampering or sync lost. Hard dropping tunnel!");
return Err("Crypto drop".into());
}
error!(error = ?e, "Codec inbound failed");
return Err(format!("Codec error: {:?}", e));
}
}
}
} // Лок кодека отпущен!
// Обрабатываем фреймы (I/O) без лока, не мешая Writer Task
for frame in frames {
handler.handle(frame).await;
}
}
}
}
Ok::<(), String>(())
});
// ==========================================
// 2. WRITER TASK (Только шифрование и отправка)
// ==========================================
let writer_handle = tokio::spawn(async move {
let mut outbound = outbound;
let mut control_rx = control_rx;
let mut data_rx = data_rx;
let mut heartbeat = tokio::time::interval(std::time::Duration::from_secs(15));
loop {
tokio::select! {
biased; // Приоритет сверху вниз
_ = token_writer.cancelled() => {
info!("Writer Task: Shutdown signal received.");
break;
} }
// FAST TRACK: Управляющие команды
msg_opt = control_rx.recv() => {
if let Some(msg) = msg_opt {
Self::handle_outbound(&mut outbound, &codec_writer, msg).await?;
} else {
break;
}
}
// Пинг
_ = heartbeat.tick() => { _ = heartbeat.tick() => {
let msg = MuxMessage { stream_id: 0, frame_type: FrameType::Heartbeat, data: Bytes::new() }; let msg = MuxMessage { stream_id: 0, frame_type: FrameType::Heartbeat, data: Bytes::new() };
Self::handle_outbound(&mut outbound, &mut codec, msg).await?; Self::handle_outbound(&mut outbound, &codec_writer, msg).await?;
} }
msg_opt = mux_rx.recv() => { // SLOW TRACK: Данные
msg_opt = data_rx.recv() => {
if let Some(msg) = msg_opt { if let Some(msg) = msg_opt {
Self::handle_outbound(&mut outbound, &mut codec, msg).await?; Self::handle_outbound(&mut outbound, &codec_writer, msg).await?;
} else { } else {
break; break;
} }
} }
} }
} }
Ok(()) Ok::<(), String>(())
});
// ==========================================
// Ожидаем завершения обеих тасок.
// Если одна падает с ошибкой, убиваем туннель.
// ==========================================
let res = tokio::select! {
res = reader_handle => res.unwrap_or_else(|e| Err(format!("Reader panic: {}", e))),
res = writer_handle => res.unwrap_or_else(|e| Err(format!("Writer panic: {}", e))),
};
if let Err(e) = &res {
error!("TunnelEngine critical failure: {}", e);
} }
async fn process_inbound( res
inbound: &mut OwnedReadHalf,
codec: &mut Codec,
read_buf: &mut BytesMut,
handler: &Arc<StreamHandler>,
) -> Result<(), String> {
let n = inbound
.read_buf(read_buf)
.await
.map_err(|e| e.to_string())?;
if n == 0 && read_buf.is_empty() {
netrunner_logger::info!("Connection closed by peer (EOF detected)");
return Err("EOF".into());
}
loop {
match codec.inbound(read_buf) {
Ok(Some(frame)) => {
handler.handle(frame).await;
}
Ok(None) => break,
Err(e) => {
if e.action == ErrorAction::Wait {
break;
}
if e.action == ErrorAction::Drop {
// ТСПУ подмешал мусор ИЛИ ключи не совпали.
// Мгновенный выход с ошибкой приведет к обрыву TCP-соединения.
netrunner_logger::error!(
"CRITICAL: Crypto tampering or sync lost. Hard dropping tunnel!"
);
return Err("Crypto drop".into());
}
error!(error = ?e, "Codec inbound failed");
return Err(format!("Codec error: {:?}", e));
}
}
}
Ok(())
} }
async fn handle_outbound( async fn handle_outbound(
outbound: &mut OwnedWriteHalf, outbound: &mut OwnedWriteHalf,
codec: &mut Codec, codec: &Arc<Mutex<Codec>>,
msg: MuxMessage, msg: MuxMessage,
) -> Result<(), String> { ) -> Result<(), String> {
const MAX_CHUNK_SIZE: usize = 16000; const MAX_CHUNK_SIZE: usize = 16000;
@@ -123,37 +185,45 @@ impl TunnelEngine {
let stream_id = msg.stream_id; let stream_id = msg.stream_id;
let frame_type = msg.frame_type; let frame_type = msg.frame_type;
// Вектор зашифрованных пакетов. Собираем их быстро под локом.
let mut packets = Vec::new();
{
// Берем лок кодека только для шифрования
let mut c = codec.lock().await;
if data.is_empty() { if data.is_empty() {
match codec.encrypt_data(stream_id, frame_type.clone(), Bytes::new()) { match c.encrypt_data(stream_id, frame_type.clone(), Bytes::new()) {
Ok(pkt) => { Ok(pkt) => packets.push(pkt),
outbound.write_all(&pkt).await.map_err(|e| e.to_string())?;
}
Err(e) => { Err(e) => {
error!(stream_id, error = ?e, "Encryption failed for empty message"); error!(stream_id, error = ?e, "Encryption failed for empty message");
return Err(format!("Encryption error: {:?}", e)); return Err(format!("Encryption error: {:?}", e));
} }
} }
return Ok(()); } else {
}
while !data.is_empty() { while !data.is_empty() {
let chunk_size = std::cmp::min(data.len(), MAX_CHUNK_SIZE); let chunk_size = std::cmp::min(data.len(), MAX_CHUNK_SIZE);
let chunk = data.split_to(chunk_size); let chunk = data.split_to(chunk_size);
match codec.encrypt_data(stream_id, frame_type.clone(), chunk) { match c.encrypt_data(stream_id, frame_type.clone(), chunk) {
Ok(pkt) => { Ok(pkt) => packets.push(pkt),
outbound.write_all(&pkt).await.map_err(|e| {
error!(stream_id, error = %e, "Failed to write encrypted data to network");
e.to_string()
})?;
}
Err(e) => { Err(e) => {
error!(stream_id, error = ?e, "Encryption failed for chunked message"); error!(stream_id, error = ?e, "Encryption failed for chunked message");
return Err(format!("Encryption error: {:?}", e)); return Err(format!("Encryption error: {:?}", e));
} }
} }
} }
}
} // Лок кодека отпущен!
// Выполняем I/O операцию (которая может зависнуть при плохой сети) БЕЗ лока кодека.
// Это позволяет Reader Task продолжать читать сеть!
for pkt in packets {
outbound.write_all(&pkt).await.map_err(|e| {
error!(stream_id, error = %e, "Failed to write encrypted data to network");
e.to_string()
})?;
}
debug!(stream_id, "Outbound packet sent successfully"); debug!(stream_id, "Outbound packet sent successfully");
Ok(()) Ok(())
+3 -2
View File
@@ -4,5 +4,6 @@ pub mod engine;
pub mod handler; pub mod handler;
pub mod muxer; pub mod muxer;
pub const BUF_SIZE: usize = 65536; pub const TCP_BUF_SIZE: usize = 1024 * 512;
pub const CHANNEL_SIZE: usize = 16; pub const UDP_BUF_SIZE: usize = 1024 * 64;
pub const MESSAGE_CHANNEL_SIZE: usize = 1024 * 16;
+28 -35
View File
@@ -1,10 +1,9 @@
use crate::protocol::codec::frame::FrameType; use crate::protocol::codec::frame::FrameType;
use bytes::Bytes; use bytes::Bytes;
use dashmap::DashMap; // Добавь в Cargo.toml: dashmap = "6.0" use dashmap::DashMap;
use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::mpsc::error::SendError; use tokio::sync::mpsc::{error::SendError, Sender};
use tokio::sync::mpsc::Sender;
pub struct IdGenerator { pub struct IdGenerator {
counter: AtomicU32, counter: AtomicU32,
@@ -31,15 +30,21 @@ pub struct MuxMessage {
#[derive(Clone)] #[derive(Clone)]
pub struct Muxer { pub struct Muxer {
to_network: Sender<MuxMessage>, control_tx: Sender<MuxMessage>,
data_tx: Sender<MuxMessage>,
streams: Arc<DashMap<u32, Sender<Bytes>>>, streams: Arc<DashMap<u32, Sender<Bytes>>>,
id_gen: Arc<IdGenerator>, id_gen: Arc<IdGenerator>,
} }
impl Muxer { impl Muxer {
pub fn new(to_network: Sender<MuxMessage>, is_client: bool) -> Self { pub fn new(
control_tx: Sender<MuxMessage>,
data_tx: Sender<MuxMessage>,
is_client: bool,
) -> Self {
Self { Self {
to_network, control_tx,
data_tx,
streams: Arc::new(DashMap::new()), streams: Arc::new(DashMap::new()),
id_gen: Arc::new(IdGenerator::new(is_client)), id_gen: Arc::new(IdGenerator::new(is_client)),
} }
@@ -49,30 +54,19 @@ impl Muxer {
self.id_gen.next() self.id_gen.next()
} }
// Обычные данные летят в канал с низким приоритетом
pub async fn send_to_netwrok(&self, message: MuxMessage) -> Result<(), SendError<MuxMessage>> { pub async fn send_to_netwrok(&self, message: MuxMessage) -> Result<(), SendError<MuxMessage>> {
self.to_network.send(message).await self.data_tx.send(message).await
}
pub fn register_stream(&self, stream_id: u32, tx: Sender<Bytes>) {
self.streams.insert(stream_id, tx);
netrunner_logger::debug!(
stream_id,
total_active = self.streams.len(),
"MUXER: [REGISTER] Stream added"
);
}
pub fn remove_stream(&self, stream_id: u32) {
self.streams.remove(&stream_id);
} }
// Управляющие фреймы летят в VIP-канал
pub async fn send_control( pub async fn send_control(
&self, &self,
stream_id: u32, stream_id: u32,
f_type: FrameType, f_type: FrameType,
data: Bytes, data: Bytes,
) -> Result<(), String> { ) -> Result<(), String> {
self.to_network self.control_tx
.send(MuxMessage { .send(MuxMessage {
stream_id, stream_id,
frame_type: f_type, frame_type: f_type,
@@ -82,32 +76,31 @@ impl Muxer {
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
} }
pub fn register_stream(&self, stream_id: u32, tx: Sender<Bytes>) {
self.streams.insert(stream_id, tx);
}
pub fn remove_stream(&self, stream_id: u32) {
self.streams.remove(&stream_id);
}
pub async fn dispatch_to_local(&self, stream_id: u32, data: Bytes) { pub async fn dispatch_to_local(&self, stream_id: u32, data: Bytes) {
// DashMap позволяет получить доступ к элементу без явного RwLock
let tx = self.streams.get(&stream_id).map(|r| r.value().clone()); let tx = self.streams.get(&stream_id).map(|r| r.value().clone());
if let Some(tx) = tx { if let Some(tx) = tx {
if data.is_empty() {
netrunner_logger::debug!(stream_id, "MUXER: [EOF] Forwarding EOF to local handler");
} else {
netrunner_logger::trace!(
stream_id,
len = data.len(),
"MUXER: [DISPATCH] Sending data"
);
}
if let Err(_e) = tx.send(data).await { if let Err(_e) = tx.send(data).await {
netrunner_logger::debug!( netrunner_logger::warn!(
stream_id, stream_id,
"MUXER: [WARN] Local channel closed, dropping packet" "MUXER: [INBOUND_ERR] Local channel closed, dropping packet"
); );
self.remove_stream(stream_id); self.remove_stream(stream_id);
} }
} else { } else {
// Уменьшил уровень лога до TRACE, потому что это штатная ситуация при больших буферах!
netrunner_logger::trace!( netrunner_logger::trace!(
stream_id, stream_id,
"MUXER: [IGNORE] Packet for already closed stream" len = data.len(),
"MUXER: [IGNORE] Received data for already closed stream (draining pipe)"
); );
} }
} }
+19 -6
View File
@@ -4,7 +4,7 @@ use crate::{
connection::{ClientHandler, Connection, ConnectionRole, ServerHandler, TunnelHandler}, connection::{ClientHandler, Connection, ConnectionRole, ServerHandler, TunnelHandler},
engine::TunnelEngine, engine::TunnelEngine,
muxer::Muxer, muxer::Muxer,
CHANNEL_SIZE, MESSAGE_CHANNEL_SIZE,
}, },
tlseng::profile::BrowserProfile, tlseng::profile::BrowserProfile,
}; };
@@ -22,6 +22,7 @@ pub struct Network {
role: ConnectionRole, role: ConnectionRole,
remote_proxy_addr: Option<String>, remote_proxy_addr: Option<String>,
} }
impl Network { impl Network {
pub fn new( pub fn new(
host: String, host: String,
@@ -131,8 +132,12 @@ impl Network {
} }
} }
let (mux_tx, mux_rx) = tokio::sync::mpsc::channel(CHANNEL_SIZE * 48); // --- ИЗМЕНЕНИЯ ЗДЕСЬ: Создаем два канала ---
let muxer = Muxer::new(mux_tx, true); let (control_tx, control_rx) = tokio::sync::mpsc::channel(100_000);
let (data_tx, data_rx) = tokio::sync::mpsc::channel(100_000);
// Передаем оба трансмиттера в Muxer
let muxer = Muxer::new(control_tx, data_tx, true);
let handler = std::sync::Arc::new(crate::proxy::connection::handler::StreamHandler::new( let handler = std::sync::Arc::new(crate::proxy::connection::handler::StreamHandler::new(
muxer.clone(), muxer.clone(),
@@ -144,13 +149,21 @@ impl Network {
outbound, outbound,
codec, codec,
read_buf: sh_buf, read_buf: sh_buf,
mux_rx, control_rx,
data_rx,
handler, handler,
token, token,
}; };
tokio::spawn(async move { engine.run().await }); tokio::spawn(async move {
if let Err(e) = engine.run().await {
netrunner_logger::error!(
"CRITICAL: Tunnel Engine died: {}. Restarting process...",
e
);
std::process::exit(1);
}
});
Ok(muxer) Ok(muxer)
} }