支持无tun模式

This commit is contained in:
lbl8603
2024-06-15 20:52:35 +08:00
parent 0bc7115102
commit 66129c2a24
10 changed files with 653 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
pub mod tcp;
pub mod udp;
+46
View File
@@ -0,0 +1,46 @@
use crate::out_mapping::tcp::tcp_copy;
use crossbeam_utils::atomic::AtomicCell;
use lwip_rs::tcp_stream::TcpStream as LwIpTcpStream;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use vnt::handle::CurrentDeviceInfo;
pub async fn tcp_mapping_listen(
tcp_listener: TcpListener,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
dest: SocketAddr,
) {
loop {
let (stream, addr) = match tcp_listener.accept().await {
Ok((stream, addr)) => (stream, addr),
Err(e) => {
log::warn!("tcp_mapping_listen {:?} dest {}", e, dest);
continue;
}
};
let current_info = current_device.load();
if current_info.virtual_ip.is_unspecified() {
continue;
}
if let IpAddr::V4(ip) = dest.ip() {
if ip == current_info.virtual_ip {
//防止用错参数的
log::warn!("目的地址不能是本地虚拟ip tcp->{}", dest);
continue;
}
}
let src = SocketAddr::new(IpAddr::V4(current_info.virtual_ip), addr.port());
tokio::spawn(async move {
match LwIpTcpStream::connect(src, dest, Duration::from_secs(5)).await {
Ok(lw_tcp) => {
tcp_copy(lw_tcp, stream);
}
Err(e) => {
log::warn!("{} {}->{} {}", addr, src, dest, e);
}
};
});
}
}
+63
View File
@@ -0,0 +1,63 @@
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::Arc;
use std::time::Instant;
use crossbeam_utils::atomic::AtomicCell;
use parking_lot::Mutex;
use tokio::net::UdpSocket;
use lwip_rs::udp::UdpSocketWrite;
use vnt::handle::CurrentDeviceInfo;
pub async fn udp_mapping_start(
udp: UdpSocket,
lwip_udp_write: UdpSocketWrite,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
in_udp_map: &Arc<
Mutex<
HashMap<
(SocketAddr, SocketAddr),
(Arc<UdpSocket>, Option<SocketAddr>, Arc<AtomicCell<Instant>>),
>,
>,
>,
dest: SocketAddr,
) {
let udp = Arc::new(udp);
let mut buf = [0u8; 65536];
loop {
let (len, addr) = match udp.recv_from(&mut buf).await {
Ok(rs) => rs,
Err(e) => {
log::warn!("recv_from {} {}", dest, e);
continue;
}
};
let current_info = current_device.load();
if current_info.virtual_ip.is_unspecified() {
continue;
}
if let IpAddr::V4(ip) = dest.ip() {
if ip == current_info.virtual_ip {
//防止用错参数的
log::warn!("目的地址不能是本地虚拟ip udp->{}", dest);
continue;
}
}
let src = SocketAddr::new(IpAddr::V4(current_info.virtual_ip), addr.port());
in_udp_map.lock().insert(
(dest, src),
(
udp.clone(),
Some(addr),
Arc::new(AtomicCell::new(Instant::now())),
),
);
if let Err(e) = lwip_udp_write.send(&buf[..len], &src, &dest) {
log::warn!("lwip_udp_write {}->{} {}", src, dest, e);
}
}
}