fixes udp and mtu
This commit is contained in:
+2
-2
@@ -84,12 +84,12 @@ impl SessionManager {
|
|||||||
|
|
||||||
#[cfg(any(target_os = "android", target_os = "ios"))]
|
#[cfg(any(target_os = "android", target_os = "ios"))]
|
||||||
{
|
{
|
||||||
config = config.disable_routing().with_mtu(1280);
|
config = config.disable_routing().with_mtu(1500);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
{
|
{
|
||||||
config = config.with_mtu(1280);
|
config = config.with_mtu(1500);
|
||||||
}
|
}
|
||||||
|
|
||||||
NetworkConfig::init_global(config.mtu);
|
NetworkConfig::init_global(config.mtu);
|
||||||
|
|||||||
+1
-1
@@ -24,7 +24,7 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
// ==================================================
|
// ==================================================
|
||||||
let config = EngineConfig::new(&remote_address)
|
let config = EngineConfig::new(&remote_address)
|
||||||
.with_cache_path(".")
|
.with_cache_path(".")
|
||||||
.with_mtu(1280);
|
.with_mtu(1500);
|
||||||
|
|
||||||
// ВАЖНО: Инициализируем глобальные настройки сети (MTU, размеры буферов Muxer'а)
|
// ВАЖНО: Инициализируем глобальные настройки сети (MTU, размеры буферов Muxer'а)
|
||||||
NetworkConfig::init_global(config.mtu);
|
NetworkConfig::init_global(config.mtu);
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use smoltcp::{
|
|||||||
time::Instant,
|
time::Instant,
|
||||||
wire::IpEndpoint,
|
wire::IpEndpoint,
|
||||||
};
|
};
|
||||||
use std::time::Duration;
|
use std::{collections::HashSet, time::Duration};
|
||||||
use tokio::sync::{mpsc, oneshot};
|
use tokio::sync::{mpsc, oneshot};
|
||||||
// Добавили trace для частых логов (попакетно) и debug для состояний
|
// Добавили trace для частых логов (попакетно) и debug для состояний
|
||||||
use netrunner_logger::{debug, error, info, trace, warn};
|
use netrunner_logger::{debug, error, info, trace, warn};
|
||||||
@@ -226,8 +226,8 @@ const UDP_TIMEOUT: Duration = Duration::from_secs(60);
|
|||||||
|
|
||||||
pub struct UdpConnection {
|
pub struct UdpConnection {
|
||||||
core: ConnectionCore,
|
core: ConnectionCore,
|
||||||
client_endpoint: Option<IpEndpoint>,
|
client_endpoints: HashSet<IpEndpoint>,
|
||||||
last_activity: Instant,
|
last_activity: std::time::Instant, // Системное время для таймаутов
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UdpConnection {
|
impl UdpConnection {
|
||||||
@@ -237,93 +237,57 @@ impl UdpConnection {
|
|||||||
|
|
||||||
let conn = Self {
|
let conn = Self {
|
||||||
core,
|
core,
|
||||||
client_endpoint: None,
|
client_endpoints: HashSet::new(), // Инициализируем пустое множество
|
||||||
last_activity: Instant::now(),
|
last_activity: std::time::Instant::now(),
|
||||||
};
|
};
|
||||||
|
|
||||||
(conn, rx_from_smol, tx_to_smol)
|
(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 {
|
||||||
// 1. Получаем текущее время системы в миллисекундах
|
// Проверка таймаутов (остается твоя рабочая)
|
||||||
let now_ms = std::time::SystemTime::now()
|
if self.last_activity.elapsed() > UDP_TIMEOUT {
|
||||||
.duration_since(std::time::UNIX_EPOCH)
|
debug!(%self.core.handle, "UDP Session closed due to timeout");
|
||||||
.unwrap_or_default()
|
|
||||||
.as_millis() as i64;
|
|
||||||
|
|
||||||
// 2. Считаем разницу (сколько мс прошло с последней активности)
|
|
||||||
let elapsed_ms = now_ms - self.last_activity.total_millis();
|
|
||||||
|
|
||||||
// 3. Сравниваем с UDP_TIMEOUT (переводим его тоже в мс)
|
|
||||||
if elapsed_ms > UDP_TIMEOUT.as_millis() as i64 {
|
|
||||||
debug!(
|
|
||||||
%self.core.handle,
|
|
||||||
"UDP Session closed due to {}s timeout",
|
|
||||||
UDP_TIMEOUT.as_secs()
|
|
||||||
);
|
|
||||||
socket.close();
|
socket.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ЧИТАЕМ ИЗ SMOLTCP (от клиента) И ШЛЕМ В ТУННЕЛЬ
|
||||||
if socket.can_recv() {
|
if socket.can_recv() {
|
||||||
let target_endpoint = socket.endpoint();
|
|
||||||
while let Ok((data, metadata)) = socket.recv() {
|
while let Ok((data, metadata)) = socket.recv() {
|
||||||
let source_endpoint = metadata.endpoint;
|
let source_endpoint = metadata.endpoint;
|
||||||
|
|
||||||
if self.client_endpoint.is_none() {
|
// ЗАПОМИНАЕМ ВСЕ ПОРТЫ КЛИЕНТА, КОТОРЫЕ СЮДА СТУЧАТСЯ
|
||||||
|
if self.client_endpoints.insert(source_endpoint) {
|
||||||
info!(
|
info!(
|
||||||
%self.core.handle,
|
%self.core.handle,
|
||||||
source = %source_endpoint,
|
source = %source_endpoint,
|
||||||
target = %target_endpoint,
|
"Registered new client port for UDP session"
|
||||||
"UDP Session Established. Pinning endpoint."
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
self.client_endpoint = Some(source_endpoint);
|
|
||||||
|
|
||||||
trace!(
|
|
||||||
%self.core.handle,
|
|
||||||
source = %source_endpoint,
|
|
||||||
target = %target_endpoint,
|
|
||||||
bytes = data.len(),
|
|
||||||
"Forwarded UDP datagram from smoltcp to Muxer"
|
|
||||||
);
|
|
||||||
|
|
||||||
if self.core.tx.try_send(Bytes::copy_from_slice(data)).is_ok() {
|
if self.core.tx.try_send(Bytes::copy_from_slice(data)).is_ok() {
|
||||||
self.last_activity = Instant::now();
|
self.last_activity = std::time::Instant::now();
|
||||||
} else {
|
|
||||||
debug!(%self.core.handle, "Muxer TX channel full or closed, dropping UDP datagram");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if socket.can_send() {
|
// ЧИТАЕМ ИЗ ТУННЕЛЯ И ШЛЕМ В SMOLTCP (клиенту)
|
||||||
if let Some(client_endpoint) = self.client_endpoint {
|
if socket.can_send() && !self.client_endpoints.is_empty() {
|
||||||
loop {
|
loop {
|
||||||
match self.core.rx.try_recv() {
|
match self.core.rx.try_recv() {
|
||||||
Ok(data) => match socket.send_slice(&data, client_endpoint) {
|
Ok(data) => {
|
||||||
Ok(_) => {
|
// БРОАДКАСТ: Отправляем ответ на ВСЕ порты, которые мы запомнили
|
||||||
info!(
|
for endpoint in &self.client_endpoints {
|
||||||
%self.core.handle,
|
let _ = socket.send_slice(&data, *endpoint);
|
||||||
bytes = data.len(),
|
|
||||||
target = %client_endpoint,
|
|
||||||
"🟢 SUCCESS: Received UDP from tunnel, pushed to smoltcp!"
|
|
||||||
);
|
|
||||||
self.last_activity = smoltcp::time::Instant::now();
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
error!(%self.core.handle, "Failed to send UDP datagram: {:?}", e);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(mpsc::error::TryRecvError::Empty) => {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
Err(mpsc::error::TryRecvError::Disconnected) => {
|
|
||||||
// Сервер разорвал соединение!
|
|
||||||
debug!(%self.core.handle, "Muxer channel disconnected, closing UDP socket");
|
|
||||||
socket.close();
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
self.last_activity = std::time::Instant::now();
|
||||||
|
}
|
||||||
|
Err(mpsc::error::TryRecvError::Empty) => break,
|
||||||
|
Err(mpsc::error::TryRecvError::Disconnected) => {
|
||||||
|
debug!(%self.core.handle, "Muxer channel disconnected");
|
||||||
|
socket.close();
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ impl Network {
|
|||||||
let addr = format!("{}:{}", self.host, self.port);
|
let addr = format!("{}:{}", self.host, self.port);
|
||||||
|
|
||||||
// Инициализируем глобальный конфиг сети (MTU, размеры буферов)
|
// Инициализируем глобальный конфиг сети (MTU, размеры буферов)
|
||||||
NetworkConfig::init_global(1280);
|
NetworkConfig::init_global(1500);
|
||||||
|
|
||||||
match self.role {
|
match self.role {
|
||||||
ConnectionRole::Client => {
|
ConnectionRole::Client => {
|
||||||
|
|||||||
Reference in New Issue
Block a user