支持tap网卡,优化tun网卡配置
This commit is contained in:
+47
-19
@@ -7,15 +7,17 @@ use parking_lot::Mutex;
|
||||
use p2p_channel::boot::Boot;
|
||||
use p2p_channel::channel::{Channel, Route, RouteKey};
|
||||
use p2p_channel::punch::NatInfo;
|
||||
use crate::handle::{ConnectStatus, CurrentDeviceInfo, heartbeat_handler, PeerDeviceInfo, punch_handler, recv_handler, registration_handler, tun_handler};
|
||||
use crate::handle::{ConnectStatus, CurrentDeviceInfo, heartbeat_handler, PeerDeviceInfo, punch_handler, recv_handler, registration_handler, tap_handler, tun_handler};
|
||||
use crate::nat::NatTest;
|
||||
use crate::tun_device;
|
||||
use crate::tun_device::TunReader;
|
||||
use crate::{tap_device, tun_device};
|
||||
use crate::tap_device::TapWriter;
|
||||
use crate::tun_device::TunWriter;
|
||||
|
||||
pub struct Switch {
|
||||
name: String,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
tun_reader: TunReader,
|
||||
tun_writer: Option<TunWriter>,
|
||||
tap_writer: Option<TapWriter>,
|
||||
nat_channel: Channel<Ipv4Addr>,
|
||||
/// 0. 机器纪元,每一次上线或者下线都会增1,用于感知网络中机器变化
|
||||
/// 服务端和客户端的不一致,则服务端会推送新的设备列表
|
||||
@@ -38,14 +40,40 @@ impl Switch {
|
||||
let virtual_ip = Ipv4Addr::from(response.virtual_ip);
|
||||
let virtual_gateway = Ipv4Addr::from(response.virtual_gateway);
|
||||
let virtual_netmask = Ipv4Addr::from(response.virtual_netmask);
|
||||
let current_device = Arc::new(AtomicCell::new(CurrentDeviceInfo::new(virtual_ip, virtual_gateway, virtual_netmask, config.server_address)));
|
||||
|
||||
let local_ip = crate::nat::local_ip()?;
|
||||
let local_port = channel.local_addr()?.port();
|
||||
// NAT检测
|
||||
let nat_test = NatTest::new(config.nat_test_server.clone(), Ipv4Addr::from(response.public_ip), response.public_port as u16, local_ip, local_port);
|
||||
// tun通道
|
||||
let (tun_writer, tun_reader) = tun_device::create_tun(virtual_ip, virtual_netmask, virtual_gateway)?;
|
||||
|
||||
let (current_device, tun_writer, tap_writer) = if config.tap {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
//删除switch的tun网卡避免ip冲突,因为非正常退出会保留网卡
|
||||
tun_device::delete_tun();
|
||||
}
|
||||
let (tap_writer, tap_reader, mac) = tap_device::create_tap(virtual_ip, virtual_netmask, virtual_gateway)?;
|
||||
let current_device = Arc::new(AtomicCell::new(CurrentDeviceInfo::new(virtual_ip, virtual_gateway, virtual_netmask,
|
||||
config.server_address, mac)));
|
||||
//tap数据处理
|
||||
tap_handler::start(channel.sender()?, tap_reader.clone(), tap_writer.clone(), current_device.clone());
|
||||
(current_device, None, Some(tap_writer))
|
||||
} else {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
//删除switch的tap网卡避免ip冲突,非正常退出会保留网卡
|
||||
tap_device::delete_tap();
|
||||
}
|
||||
// tun通道
|
||||
let (tun_writer, tun_reader) = tun_device::create_tun(virtual_ip, virtual_netmask, virtual_gateway)?;
|
||||
let current_device = Arc::new(AtomicCell::new(CurrentDeviceInfo::new(virtual_ip, virtual_gateway, virtual_netmask, config.server_address, [0, 0, 0, 0, 0, 0])));
|
||||
//tun数据接收处理
|
||||
tun_handler::start(channel.sender()?, tun_reader.clone(), tun_writer.clone(), current_device.clone());
|
||||
(current_device, Some(tun_writer), None)
|
||||
};
|
||||
//外部数据接收处理
|
||||
let channel_recv_handler = recv_handler::RecvHandler::new(channel.try_clone()?, current_device.clone(), device_list.clone(), register.clone(),
|
||||
nat_test.clone(), tun_writer.clone(), tap_writer.clone(), connect_status.clone(), peer_nat_info_map.clone());
|
||||
recv_handler::start(channel_recv_handler);
|
||||
// 定时心跳
|
||||
heartbeat_handler::start_heartbeat(channel.sender()?, device_list.clone(), current_device.clone());
|
||||
// 空闲检查
|
||||
@@ -54,19 +82,12 @@ impl Switch {
|
||||
punch_handler::start_cone(punch.try_clone()?, current_device.clone());
|
||||
punch_handler::start_symmetric(punch, current_device.clone());
|
||||
punch_handler::start_punch(nat_test.clone(), device_list.clone(), channel.sender()?, current_device.clone());
|
||||
//tun数据接收处理
|
||||
tun_handler::start(channel.sender()?, tun_reader.clone(), tun_writer.clone(), current_device.clone());
|
||||
//外部数据接收处理
|
||||
let channel_recv_handler = recv_handler::RecvHandler::new(channel.try_clone()?, current_device.clone(), device_list.clone(), register.clone(),
|
||||
nat_test.clone(), tun_writer.clone(), connect_status.clone(), peer_nat_info_map.clone());
|
||||
for _ in 0..2 {
|
||||
recv_handler::start(channel_recv_handler.try_clone()?);
|
||||
}
|
||||
log::info!("switch启动成功");
|
||||
Ok(Switch {
|
||||
name: config.name,
|
||||
current_device,
|
||||
tun_reader,
|
||||
tun_writer,
|
||||
tap_writer,
|
||||
nat_channel: channel,
|
||||
nat_test,
|
||||
device_list,
|
||||
@@ -108,7 +129,12 @@ impl Switch {
|
||||
self.nat_channel.route_table()
|
||||
}
|
||||
pub fn stop(&self) -> io::Result<()> {
|
||||
self.tun_reader.close();
|
||||
if let Some(tap) = &self.tap_writer {
|
||||
tap.close()?;
|
||||
}
|
||||
if let Some(tun) = &self.tun_writer {
|
||||
tun.close()?;
|
||||
}
|
||||
self.nat_channel.close()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -116,6 +142,7 @@ impl Switch {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
pub tap: bool,
|
||||
pub token: String,
|
||||
pub device_id: String,
|
||||
pub name: String,
|
||||
@@ -124,12 +151,13 @@ pub struct Config {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn new(token: String,
|
||||
pub fn new(tap: bool, token: String,
|
||||
device_id: String,
|
||||
name: String,
|
||||
server_address: SocketAddr,
|
||||
nat_test_server: Vec<SocketAddr>, ) -> Self {
|
||||
Self {
|
||||
tap,
|
||||
token,
|
||||
device_id,
|
||||
name,
|
||||
|
||||
@@ -1,45 +1,60 @@
|
||||
use std::{io, thread};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::{io, thread};
|
||||
|
||||
use chrono::Local;
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use rand::prelude::SliceRandom;
|
||||
|
||||
use p2p_channel::channel::Route;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
use p2p_channel::channel::Route;
|
||||
use p2p_channel::idle::Idle;
|
||||
|
||||
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
|
||||
use crate::protocol::{control_packet, MAX_TTL, NetPacket, Protocol, Version};
|
||||
use crate::protocol::control_packet::PingPacket;
|
||||
use crate::protocol::{control_packet, NetPacket, Protocol, Version, MAX_TTL};
|
||||
|
||||
pub fn start_idle(idle: Idle<Ipv4Addr>, sender: Sender<Ipv4Addr>) {
|
||||
thread::Builder::new().name("idle".into()).spawn(move || {
|
||||
if let Err(e) = start_idle_(idle, sender) {
|
||||
log::info!("空闲检测线程停止:{:?}",e);
|
||||
}
|
||||
}).unwrap();
|
||||
thread::Builder::new()
|
||||
.name("idle".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = start_idle_(idle, sender) {
|
||||
log::info!("空闲检测线程停止:{:?}", e);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn start_idle_(idle: Idle<Ipv4Addr>, sender: Sender<Ipv4Addr>) -> io::Result<()> {
|
||||
loop {
|
||||
let (idle_status, peer_ips, route) = idle.next_idle()?;
|
||||
log::warn!("peer_ip:{:?},route:{:?},idle_status:{:?}",peer_ips,route,idle_status);
|
||||
log::warn!(
|
||||
"peer_ip:{:?},route:{:?},idle_status:{:?}",
|
||||
peer_ips,
|
||||
route,
|
||||
idle_status
|
||||
);
|
||||
for peer_ip in peer_ips {
|
||||
sender.remove_route(&peer_ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_heartbeat(sender: Sender<Ipv4Addr>, device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>, current_device: Arc<AtomicCell<CurrentDeviceInfo>>) {
|
||||
thread::Builder::new().name("heartbeat".into()).spawn(move || {
|
||||
if let Err(e) = start_heartbeat_(sender, device_list, current_device) {
|
||||
log::info!("空闲检测线程停止:{:?}",e);
|
||||
}
|
||||
}).unwrap();
|
||||
pub fn start_heartbeat(
|
||||
sender: Sender<Ipv4Addr>,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
) {
|
||||
thread::Builder::new()
|
||||
.name("heartbeat".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = start_heartbeat_(sender, device_list, current_device) {
|
||||
log::info!("空闲检测线程停止:{:?}", e);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn set_now_time(packet: &mut NetPacket<[u8; 16]>) -> io::Result<()> {
|
||||
@@ -49,7 +64,11 @@ fn set_now_time(packet: &mut NetPacket<[u8; 16]>) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_heartbeat_(sender: Sender<Ipv4Addr>, device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>, current_device: Arc<AtomicCell<CurrentDeviceInfo>>) -> io::Result<()> {
|
||||
fn start_heartbeat_(
|
||||
sender: Sender<Ipv4Addr>,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
) -> io::Result<()> {
|
||||
let mut net_packet = NetPacket::new([0u8; 16])?;
|
||||
net_packet.set_version(Version::V1);
|
||||
net_packet.set_protocol(Protocol::Control);
|
||||
@@ -71,7 +90,10 @@ fn start_heartbeat_(sender: Sender<Ipv4Addr>, device_list: Arc<Mutex<(u16, Vec<P
|
||||
set_now_time(&mut net_packet)?;
|
||||
net_packet.first_set_ttl(MAX_TTL);
|
||||
net_packet.set_destination(peer.virtual_ip);
|
||||
if sender.send_to_id(net_packet.buffer(), &peer.virtual_ip).is_err() {
|
||||
if sender
|
||||
.send_to_id(net_packet.buffer(), &peer.virtual_ip)
|
||||
.is_err()
|
||||
{
|
||||
//没有路由则发送到网关
|
||||
let _ = sender.send_to_addr(net_packet.buffer(), current_device.connect_server);
|
||||
//再随机发送到其他地址,看有没有客户端符合转发条件
|
||||
@@ -97,15 +119,20 @@ fn start_heartbeat_(sender: Sender<Ipv4Addr>, device_list: Arc<Mutex<(u16, Vec<P
|
||||
}
|
||||
set_now_time(&mut net_packet)?;
|
||||
net_packet.set_destination(current_device.virtual_gateway());
|
||||
if let Err(e) = sender.send_to_addr(net_packet.buffer(), current_device.connect_server) {
|
||||
log::warn!("connect_server:{:?},e:{:?}",current_device.connect_server,e);
|
||||
if let Err(e) = sender.send_to_addr(net_packet.buffer(), current_device.connect_server)
|
||||
{
|
||||
log::warn!(
|
||||
"connect_server:{:?},e:{:?}",
|
||||
current_device.connect_server,
|
||||
e
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for (peer_ip, route) in sender.route_table().iter() {
|
||||
set_now_time(&mut net_packet)?;
|
||||
net_packet.set_destination(*peer_ip);
|
||||
if let Err(e) = sender.send_to_route(net_packet.buffer(), &route.route_key()) {
|
||||
log::warn!("peer_ip:{:?},route:{:?},e:{:?}",peer_ip,route,e);
|
||||
log::warn!("peer_ip:{:?},route:{:?},e:{:?}", peer_ip, route, e);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
@@ -114,4 +141,4 @@ fn start_heartbeat_(sender: Sender<Ipv4Addr>, device_list: Arc<Mutex<(u16, Vec<P
|
||||
count += 1;
|
||||
thread::sleep(Duration::from_millis(5000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
pub mod heartbeat_handler;
|
||||
pub mod punch_handler;
|
||||
pub mod registration_handler;
|
||||
pub mod tun_handler;
|
||||
pub mod tap_handler;
|
||||
pub mod punch_handler;
|
||||
pub mod recv_handler;
|
||||
pub mod registration_handler;
|
||||
|
||||
/// 是否在一个网段
|
||||
fn check_dest(dest: Ipv4Addr, virtual_netmask: Ipv4Addr, virtual_network: Ipv4Addr) -> bool {
|
||||
@@ -70,6 +71,7 @@ pub struct CurrentDeviceInfo {
|
||||
pub broadcast_address: Ipv4Addr,
|
||||
//链接的服务器地址
|
||||
pub connect_server: SocketAddr,
|
||||
pub mac:[u8;6]
|
||||
}
|
||||
|
||||
impl CurrentDeviceInfo {
|
||||
@@ -78,6 +80,7 @@ impl CurrentDeviceInfo {
|
||||
virtual_gateway: Ipv4Addr,
|
||||
virtual_netmask: Ipv4Addr,
|
||||
connect_server: SocketAddr,
|
||||
mac:[u8;6],
|
||||
) -> Self {
|
||||
let broadcast_address = (!u32::from_be_bytes(virtual_netmask.octets()))
|
||||
| u32::from_be_bytes(virtual_gateway.octets());
|
||||
@@ -92,6 +95,7 @@ impl CurrentDeviceInfo {
|
||||
virtual_network,
|
||||
broadcast_address,
|
||||
connect_server,
|
||||
mac
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
@@ -103,7 +107,3 @@ impl CurrentDeviceInfo {
|
||||
self.virtual_gateway
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,35 +1,45 @@
|
||||
use std::{io, thread};
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use protobuf::Message;
|
||||
use rand::prelude::SliceRandom;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
use p2p_channel::punch::{NatInfo, NatType, Punch};
|
||||
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
|
||||
use crate::nat::NatTest;
|
||||
use crate::proto::message::{PunchInfo, PunchNatType};
|
||||
use crate::protocol::{control_packet, MAX_TTL, NetPacket, Protocol, turn_packet, Version};
|
||||
use crate::protocol::{control_packet, turn_packet, NetPacket, Protocol, Version, MAX_TTL};
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
use p2p_channel::punch::{NatInfo, NatType, Punch};
|
||||
use parking_lot::Mutex;
|
||||
use protobuf::Message;
|
||||
use rand::prelude::SliceRandom;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::{io, thread};
|
||||
|
||||
pub fn start_cone(punch: Punch<Ipv4Addr>, current_device: Arc<AtomicCell<CurrentDeviceInfo>>) {
|
||||
thread::Builder::new().name("punch-cone".into()).spawn(move || {
|
||||
if let Err(e) = start_(true, punch, current_device) {
|
||||
log::warn!("锥形网络打洞处理线程停止 {:?}",e);
|
||||
}
|
||||
}).unwrap();
|
||||
thread::Builder::new()
|
||||
.name("punch-cone".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = start_(true, punch, current_device) {
|
||||
log::warn!("锥形网络打洞处理线程停止 {:?}", e);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
pub fn start_symmetric(punch: Punch<Ipv4Addr>, current_device: Arc<AtomicCell<CurrentDeviceInfo>>) {
|
||||
thread::Builder::new().name("punch-symmetric".into()).spawn(move || {
|
||||
if let Err(e) = start_(false, punch, current_device) {
|
||||
log::warn!("对称网络打洞处理线程停止 {:?}",e);
|
||||
}
|
||||
}).unwrap();
|
||||
thread::Builder::new()
|
||||
.name("punch-symmetric".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = start_(false, punch, current_device) {
|
||||
log::warn!("对称网络打洞处理线程停止 {:?}", e);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn start_(is_cone: bool, mut punch: Punch<Ipv4Addr>, current_device: Arc<AtomicCell<CurrentDeviceInfo>>) -> io::Result<()> {
|
||||
fn start_(
|
||||
is_cone: bool,
|
||||
mut punch: Punch<Ipv4Addr>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
) -> io::Result<()> {
|
||||
let mut packet = NetPacket::new([0u8; 12])?;
|
||||
packet.set_version(Version::V1);
|
||||
packet.first_set_ttl(1);
|
||||
@@ -49,22 +59,35 @@ fn start_(is_cone: bool, mut punch: Punch<Ipv4Addr>, current_device: Arc<AtomicC
|
||||
}
|
||||
packet.set_source(current_device.load().virtual_ip());
|
||||
packet.set_destination(peer_ip);
|
||||
log::info!("发起打洞,目标:{:?},{:?}",peer_ip,nat_info);
|
||||
log::info!("发起打洞,目标:{:?},{:?}", peer_ip, nat_info);
|
||||
if let Err(e) = punch.punch(packet.buffer(), peer_ip, nat_info) {
|
||||
log::warn!("peer_ip:{:?},e:{:?}",peer_ip,e);
|
||||
log::warn!("peer_ip:{:?},e:{:?}", peer_ip, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_punch(nat_test: NatTest, device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>, sender: Sender<Ipv4Addr>, current_device: Arc<AtomicCell<CurrentDeviceInfo>>) {
|
||||
thread::Builder::new().name("punch-send-request".into()).spawn(move || {
|
||||
if let Err(e) = start_punch_(nat_test, device_list, sender, current_device) {
|
||||
log::warn!("对称网络打洞处理线程停止 {:?}",e);
|
||||
}
|
||||
}).unwrap();
|
||||
pub fn start_punch(
|
||||
nat_test: NatTest,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
sender: Sender<Ipv4Addr>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
) {
|
||||
thread::Builder::new()
|
||||
.name("punch-send-request".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = start_punch_(nat_test, device_list, sender, current_device) {
|
||||
log::warn!("对称网络打洞处理线程停止 {:?}", e);
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn start_punch_(nat_test: NatTest, device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>, sender: Sender<Ipv4Addr>, current_device: Arc<AtomicCell<CurrentDeviceInfo>>) -> crate::Result<()> {
|
||||
fn start_punch_(
|
||||
nat_test: NatTest,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
sender: Sender<Ipv4Addr>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
) -> crate::Result<()> {
|
||||
loop {
|
||||
if sender.is_close() {
|
||||
return Ok(());
|
||||
@@ -104,19 +127,23 @@ fn start_punch_(nat_test: NatTest, device_list: Arc<Mutex<(u16, Vec<PeerDeviceIn
|
||||
}
|
||||
}
|
||||
|
||||
pub fn punch_packet(virtual_ip: Ipv4Addr, nat_info: &NatInfo, dest: Ipv4Addr) -> crate::Result<Vec<u8>> {
|
||||
pub fn punch_packet(
|
||||
virtual_ip: Ipv4Addr,
|
||||
nat_info: &NatInfo,
|
||||
dest: Ipv4Addr,
|
||||
) -> crate::Result<Vec<u8>> {
|
||||
let mut punch_reply = PunchInfo::new();
|
||||
punch_reply.reply = false;
|
||||
punch_reply.public_ip_list = nat_info.public_ips.iter().map(|i| {
|
||||
match i {
|
||||
IpAddr::V4(ip) => {
|
||||
u32::from_be_bytes(ip.octets())
|
||||
}
|
||||
punch_reply.public_ip_list = nat_info
|
||||
.public_ips
|
||||
.iter()
|
||||
.map(|i| match i {
|
||||
IpAddr::V4(ip) => u32::from_be_bytes(ip.octets()),
|
||||
IpAddr::V6(_) => {
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
}).collect();
|
||||
})
|
||||
.collect();
|
||||
punch_reply.public_port = nat_info.public_port as u32;
|
||||
punch_reply.public_port_range = nat_info.public_port_range as u32;
|
||||
punch_reply.local_ip = match nat_info.local_ip {
|
||||
@@ -137,4 +164,4 @@ pub fn punch_packet(virtual_ip: Ipv4Addr, nat_info: &NatInfo, dest: Ipv4Addr) ->
|
||||
net_packet.set_destination(dest);
|
||||
net_packet.set_payload(&bytes);
|
||||
Ok(net_packet.into_buffer())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ use protobuf::Message;
|
||||
|
||||
use p2p_channel::channel::{Channel, Route, RouteKey};
|
||||
use p2p_channel::punch::NatInfo;
|
||||
use packet::ethernet;
|
||||
use packet::icmp::{icmp, Kind};
|
||||
use packet::ip::ipv4;
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
@@ -23,6 +24,7 @@ use crate::proto::message::{DeviceList, PunchInfo, PunchNatType, RegistrationRes
|
||||
use crate::protocol::{control_packet, MAX_TTL, NetPacket, Protocol, service_packet, turn_packet, Version};
|
||||
use crate::protocol::control_packet::ControlPacket;
|
||||
use crate::protocol::error_packet::InErrorPacket;
|
||||
use crate::tap_device::TapWriter;
|
||||
use crate::tun_device::TunWriter;
|
||||
|
||||
pub fn start(mut handler: RecvHandler) {
|
||||
@@ -57,7 +59,8 @@ pub struct RecvHandler {
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
register: Arc<Register>,
|
||||
nat_test: NatTest,
|
||||
tun_writer: TunWriter,
|
||||
tun_writer: Option<TunWriter>,
|
||||
tap_writer: Option<TapWriter>,
|
||||
connect_status: Arc<AtomicCell<ConnectStatus>>,
|
||||
peer_nat_info_map: Arc<SkipMap<Ipv4Addr, NatInfo>>,
|
||||
}
|
||||
@@ -68,7 +71,8 @@ impl RecvHandler {
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
register: Arc<Register>,
|
||||
nat_test: NatTest,
|
||||
tun_writer: TunWriter,
|
||||
tun_writer: Option<TunWriter>,
|
||||
tap_writer: Option<TapWriter>,
|
||||
connect_status: Arc<AtomicCell<ConnectStatus>>,
|
||||
peer_nat_info_map: Arc<SkipMap<Ipv4Addr, NatInfo>>,
|
||||
) -> Self {
|
||||
@@ -79,6 +83,7 @@ impl RecvHandler {
|
||||
register,
|
||||
nat_test,
|
||||
tun_writer,
|
||||
tap_writer,
|
||||
connect_status,
|
||||
peer_nat_info_map,
|
||||
}
|
||||
@@ -91,6 +96,7 @@ impl RecvHandler {
|
||||
register: self.register.clone(),
|
||||
nat_test: self.nat_test.clone(),
|
||||
tun_writer: self.tun_writer.clone(),
|
||||
tap_writer: self.tap_writer.clone(),
|
||||
connect_status: self.connect_status.clone(),
|
||||
peer_nat_info_map: self.peer_nat_info_map.clone(),
|
||||
})
|
||||
@@ -103,6 +109,7 @@ impl RecvHandler {
|
||||
if net_packet.ttl() == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
net_packet.set_ttl(net_packet.ttl() - 1);
|
||||
let source = net_packet.source();
|
||||
let current_device = self.current_device.load();
|
||||
if source == current_device.virtual_ip() {
|
||||
@@ -122,7 +129,6 @@ impl RecvHandler {
|
||||
let ttl = net_packet.ttl();
|
||||
if ttl > 1 {
|
||||
// 转发
|
||||
net_packet.set_ttl(ttl - 1);
|
||||
if let Some(route) = self.channel.route(&destination) {
|
||||
if route.metric <= net_packet.ttl() {
|
||||
self.channel.send_to_route(net_packet.buffer(), &route.route_key())?;
|
||||
@@ -138,22 +144,38 @@ impl RecvHandler {
|
||||
match net_packet.protocol() {
|
||||
Protocol::Ipv4Turn => {
|
||||
let mut ipv4 = IpV4Packet::new(net_packet.payload_mut())?;
|
||||
if ipv4.protocol() == ipv4::protocol::Protocol::Icmp {
|
||||
let mut icmp_packet = icmp::IcmpPacket::new(ipv4.payload_mut())?;
|
||||
if icmp_packet.kind() == Kind::EchoRequest {
|
||||
//开启ping
|
||||
icmp_packet.set_kind(Kind::EchoReply);
|
||||
icmp_packet.update_checksum();
|
||||
ipv4.set_source_ip(destination);
|
||||
ipv4.set_destination_ip(source);
|
||||
ipv4.update_checksum();
|
||||
net_packet.set_source(destination);
|
||||
net_packet.set_destination(source);
|
||||
self.channel.send_to_route(net_packet.buffer(), route_key)?;
|
||||
return Ok(());
|
||||
if ipv4.destination_ip() != destination {
|
||||
//todo 外部数据转发
|
||||
} else {
|
||||
if ipv4.protocol() == ipv4::protocol::Protocol::Icmp {
|
||||
let mut icmp_packet = icmp::IcmpPacket::new(ipv4.payload_mut())?;
|
||||
if icmp_packet.kind() == Kind::EchoRequest {
|
||||
//开启ping
|
||||
icmp_packet.set_kind(Kind::EchoReply);
|
||||
icmp_packet.update_checksum();
|
||||
ipv4.set_source_ip(destination);
|
||||
ipv4.set_destination_ip(source);
|
||||
ipv4.update_checksum();
|
||||
net_packet.set_source(destination);
|
||||
net_packet.set_destination(source);
|
||||
self.channel.send_to_route(net_packet.buffer(), route_key)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Some(tun_writer) = &self.tun_writer {
|
||||
tun_writer.write(net_packet.payload())?;
|
||||
} else {
|
||||
if let Some(tap_writer) = &self.tap_writer {
|
||||
let mut ethernet_packet = ethernet::packet::EthernetPacket::unchecked(vec![0; 14 + ipv4.buffer.len()]);
|
||||
let source = source.octets();
|
||||
ethernet_packet.set_source(&[source[0], source[1], source[2], source[3], 123, 234]);
|
||||
ethernet_packet.set_destination(¤t_device.mac);
|
||||
ethernet_packet.set_protocol(ethernet::protocol::Protocol::Ipv4);
|
||||
ethernet_packet.payload_mut().copy_from_slice(ipv4.buffer);
|
||||
tap_writer.write(ðernet_packet.buffer)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.tun_writer.write(net_packet.payload())?;
|
||||
}
|
||||
Protocol::Service => {
|
||||
self.service(current_device, source, net_packet, route_key)?;
|
||||
@@ -195,9 +217,15 @@ impl RecvHandler {
|
||||
let virtual_ip = Ipv4Addr::from(response.virtual_ip);
|
||||
let virtual_gateway = Ipv4Addr::from(response.virtual_gateway);
|
||||
let virtual_netmask = Ipv4Addr::from(response.virtual_netmask);
|
||||
self.tun_writer.change_ip(virtual_ip, virtual_netmask, virtual_gateway, old_netmask, old_gateway)?;
|
||||
if let Some(tun_writer) = &self.tun_writer {
|
||||
tun_writer.change_ip(virtual_ip, virtual_netmask, virtual_gateway, old_netmask, old_gateway)?;
|
||||
} else {
|
||||
if let Some(tap_writer) = &self.tap_writer {
|
||||
tap_writer.change_ip(virtual_ip, virtual_netmask, virtual_gateway, old_netmask, old_gateway)?;
|
||||
}
|
||||
}
|
||||
let new_current_device = CurrentDeviceInfo::new(virtual_ip, virtual_gateway,
|
||||
virtual_netmask, current_device.connect_server);
|
||||
virtual_netmask, current_device.connect_server, current_device.mac);
|
||||
if let Err(e) = self.current_device.compare_exchange(current_device, new_current_device) {
|
||||
log::warn!("替换失败:{:?}",e);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::Local;
|
||||
use protobuf::Message;
|
||||
use p2p_channel::channel::Channel;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
use p2p_channel::channel::Channel;
|
||||
use protobuf::Message;
|
||||
|
||||
use crate::error::*;
|
||||
use crate::proto::message::{RegistrationRequest, RegistrationResponse};
|
||||
@@ -35,20 +35,14 @@ pub fn registration(
|
||||
Protocol::Service => {
|
||||
match service_packet::Protocol::from(net_packet.transport_protocol()) {
|
||||
service_packet::Protocol::RegistrationResponse => {
|
||||
let response =
|
||||
RegistrationResponse::parse_from_bytes(net_packet.payload())?;
|
||||
let response = RegistrationResponse::parse_from_bytes(net_packet.payload())?;
|
||||
Ok(response)
|
||||
}
|
||||
_ => {
|
||||
Err(Error::Warn(format!("数据错误:{:?}", net_packet)))
|
||||
}
|
||||
_ => Err(Error::Warn(format!("数据错误:{:?}", net_packet))),
|
||||
}
|
||||
}
|
||||
Protocol::Error => {
|
||||
match InErrorPacket::new(
|
||||
net_packet.transport_protocol(),
|
||||
net_packet.payload(),
|
||||
) {
|
||||
match InErrorPacket::new(net_packet.transport_protocol(), net_packet.payload()) {
|
||||
Ok(e) => match e {
|
||||
InErrorPacket::TokenError => Err(Error::Stop("token错误".to_string())),
|
||||
InErrorPacket::Disconnect => Err(Error::Warn("断开连接".to_string())),
|
||||
@@ -61,9 +55,7 @@ pub fn registration(
|
||||
Err(e) => Err(Error::Warn(format!("{:?}", e))),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
Err(Error::Warn(format!("数据错误:{:?}", net_packet)))
|
||||
}
|
||||
_ => Err(Error::Warn(format!("数据错误:{:?}", net_packet))),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -99,11 +91,13 @@ pub struct Register {
|
||||
}
|
||||
|
||||
impl Register {
|
||||
pub fn new(sender: Sender<Ipv4Addr>,
|
||||
server_address: SocketAddr,
|
||||
token: String,
|
||||
device_id: String,
|
||||
name: String, ) -> Self {
|
||||
pub fn new(
|
||||
sender: Sender<Ipv4Addr>,
|
||||
server_address: SocketAddr,
|
||||
token: String,
|
||||
device_id: String,
|
||||
name: String,
|
||||
) -> Self {
|
||||
Self {
|
||||
sender,
|
||||
server_address,
|
||||
@@ -117,18 +111,22 @@ impl Register {
|
||||
let last = self.time.load(Ordering::Relaxed);
|
||||
let new = Local::now().timestamp_millis();
|
||||
if new - last < 1000
|
||||
|| self.time
|
||||
.compare_exchange(last, new, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_err()
|
||||
|| self
|
||||
.time
|
||||
.compare_exchange(last, new, Ordering::Relaxed, Ordering::Relaxed)
|
||||
.is_err()
|
||||
{
|
||||
//短时间不重复注册
|
||||
return Ok(());
|
||||
}
|
||||
log::info!("重新连接");
|
||||
let request_packet =
|
||||
registration_request_packet(self.token.clone(),
|
||||
self.device_id.clone(),
|
||||
self.name.clone(), false).unwrap();
|
||||
let request_packet = registration_request_packet(
|
||||
self.token.clone(),
|
||||
self.device_id.clone(),
|
||||
self.name.clone(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let buf = request_packet.buffer();
|
||||
self.sender.send_to_addr(buf, self.server_address)?;
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::{io, thread};
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
use packet::arp::arp::ArpPacket;
|
||||
use packet::ethernet;
|
||||
use packet::ethernet::packet::EthernetPacket;
|
||||
use packet::icmp::icmp::IcmpPacket;
|
||||
use packet::icmp::Kind;
|
||||
use packet::ip::ipv4;
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
use crate::handle::{check_dest, CurrentDeviceInfo};
|
||||
use crate::protocol::{MAX_TTL, NetPacket, Protocol, Version};
|
||||
use crate::tap_device::{TapReader, TapWriter};
|
||||
|
||||
pub fn start(sender: Sender<Ipv4Addr>,
|
||||
tap_reader: TapReader,
|
||||
tap_writer: TapWriter,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>, ) {
|
||||
thread::Builder::new().name("tap-handler".into()).spawn(move || {
|
||||
if let Err(e) = start_(sender, tap_reader, tap_writer, current_device) {
|
||||
log::warn!("{:?}",e);
|
||||
}
|
||||
}).unwrap();
|
||||
}
|
||||
|
||||
fn start_(sender: Sender<Ipv4Addr>,
|
||||
tap_reader: TapReader,
|
||||
tap_writer: TapWriter,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>, ) -> io::Result<()> {
|
||||
let mut net_packet = NetPacket::new(vec![0u8; 4 + 8 + 1500]).unwrap();
|
||||
net_packet.set_version(Version::V1);
|
||||
net_packet.set_protocol(Protocol::Ipv4Turn);
|
||||
net_packet.set_transport_protocol(ipv4::protocol::Protocol::Ipv4.into());
|
||||
net_packet.set_ttl(MAX_TTL);
|
||||
let mut buf = [0; 2048];
|
||||
loop {
|
||||
let len = tap_reader.read(&mut buf)?;
|
||||
if len == 0 {
|
||||
continue;
|
||||
}
|
||||
let mut ethernet_packet = EthernetPacket::unchecked(&mut buf[..len]);
|
||||
if let Err(e) = handle(&mut net_packet, ¤t_device, &tap_writer, &mut ethernet_packet, &sender) {
|
||||
log::error!("tap handle{:?}",e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(net_packet: &mut NetPacket<Vec<u8>>, current_device: &AtomicCell<CurrentDeviceInfo>, tap_writer: &TapWriter, ethernet_packet: &mut EthernetPacket<&mut [u8]>, sender: &Sender<Ipv4Addr>) -> io::Result<()> {
|
||||
let current_device = current_device.load();
|
||||
match ethernet_packet.protocol() {
|
||||
ethernet::protocol::Protocol::Arp => {
|
||||
let mut out_ethernet_packet = ethernet::packet::EthernetPacket::unchecked(ethernet_packet.buffer.to_vec());
|
||||
let arp_packet = ArpPacket::unchecked(ethernet_packet.payload());
|
||||
let mut out_arp_packet = ArpPacket::unchecked(out_ethernet_packet.payload_mut());
|
||||
let sender_h = arp_packet.sender_hardware_addr();
|
||||
let sender_p = arp_packet.sender_protocol_addr();
|
||||
let target_p = arp_packet.target_protocol_addr();
|
||||
if target_p == &[0, 0, 0, 0] || sender_p == &[0, 0, 0, 0] || target_p == sender_p {
|
||||
return Ok(());
|
||||
}
|
||||
//回复一个虚假的MAC地址
|
||||
out_arp_packet.set_sender_hardware_addr(&[target_p[0], target_p[1], target_p[2], target_p[3], 123, 234]);
|
||||
out_arp_packet.set_sender_protocol_addr(target_p);
|
||||
out_arp_packet.set_target_hardware_addr(sender_h);
|
||||
out_arp_packet.set_target_protocol_addr(sender_p);
|
||||
out_arp_packet.set_op_code(2);
|
||||
out_ethernet_packet.set_source(&[target_p[0], target_p[1], target_p[2], target_p[3], 123, 234]);
|
||||
out_ethernet_packet.set_destination(sender_h);
|
||||
|
||||
tap_writer.write(&out_ethernet_packet.buffer)?;
|
||||
}
|
||||
ethernet::protocol::Protocol::Ipv4 => {
|
||||
// println!("in ethernet_packet {:?}", ethernet_packet);
|
||||
let mut ipv4_packet = IpV4Packet::unchecked(ethernet_packet.payload_mut());
|
||||
let src_ip = ipv4_packet.source_ip();
|
||||
let dest_ip = ipv4_packet.destination_ip();
|
||||
if src_ip != current_device.virtual_ip() || (!check_dest(dest_ip, current_device.virtual_netmask, current_device.virtual_network) && !dest_ip.is_broadcast()) {
|
||||
return Ok(());
|
||||
}
|
||||
if src_ip == dest_ip {
|
||||
if ipv4_packet.protocol() == ipv4::protocol::Protocol::Icmp {
|
||||
let mut icmp = IcmpPacket::unchecked(ipv4_packet.payload_mut());
|
||||
if icmp.kind() == Kind::EchoRequest {
|
||||
icmp.set_kind(Kind::EchoReply);
|
||||
icmp.update_checksum();
|
||||
let src = ipv4_packet.source_ip();
|
||||
ipv4_packet.set_source_ip(ipv4_packet.destination_ip());
|
||||
ipv4_packet.set_destination_ip(src);
|
||||
ipv4_packet.update_checksum();
|
||||
tap_writer.write(ethernet_packet.buffer)?;
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
net_packet.set_source(src_ip);
|
||||
net_packet.set_destination(dest_ip);
|
||||
let data_len = ipv4_packet.buffer.len();
|
||||
net_packet.set_payload(ipv4_packet.buffer);
|
||||
//优先发到直连到地址
|
||||
if sender.send_to_id(&net_packet.buffer()[..(12 + data_len)], &dest_ip).is_err() {
|
||||
sender.send_to_addr(&net_packet.buffer()[..(12 + data_len)], current_device.connect_server)?;
|
||||
}
|
||||
}
|
||||
p => {
|
||||
log::warn!("不支持的二层协议:{:?}",p)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::{io, thread};
|
||||
/// 接收tun数据,并且转发到udp上
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
@@ -15,7 +15,6 @@ use crate::handle::{check_dest, CurrentDeviceInfo};
|
||||
use crate::protocol::{MAX_TTL, NetPacket, Protocol, Version};
|
||||
use crate::tun_device::{TunReader, TunWriter};
|
||||
|
||||
|
||||
fn icmp(tun_writer: &TunWriter, mut ipv4_packet: IpV4Packet<&mut [u8]>) -> Result<()> {
|
||||
if ipv4_packet.protocol() == ipv4::protocol::Protocol::Icmp {
|
||||
let mut icmp = IcmpPacket::new(ipv4_packet.payload_mut())?;
|
||||
@@ -32,6 +31,7 @@ fn icmp(tun_writer: &TunWriter, mut ipv4_packet: IpV4Packet<&mut [u8]>) -> Resul
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 接收tun数据,并且转发到udp上
|
||||
#[inline]
|
||||
fn handle(sender: &Sender<Ipv4Addr>, data: &mut [u8], tun_writer: &TunWriter, current_device: CurrentDeviceInfo, net_packet: &mut NetPacket<Vec<u8>>) -> Result<()> {
|
||||
let data_len = data.len();
|
||||
@@ -68,7 +68,7 @@ fn handle(sender: &Sender<Ipv4Addr>, data: &mut [u8], tun_writer: &TunWriter, cu
|
||||
pub fn start(sender: Sender<Ipv4Addr>,
|
||||
tun_reader: TunReader,
|
||||
tun_writer: TunWriter,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>, ) {
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>) {
|
||||
thread::Builder::new().name("tun-handler".into()).spawn(move || {
|
||||
if let Err(e) = start_(sender, tun_reader, tun_writer, current_device) {
|
||||
log::warn!("{:?}",e);
|
||||
@@ -80,7 +80,7 @@ pub fn start(sender: Sender<Ipv4Addr>,
|
||||
fn start_(sender: Sender<Ipv4Addr>,
|
||||
tun_reader: TunReader,
|
||||
tun_writer: TunWriter,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>, ) -> io::Result<()> {
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>) -> io::Result<()> {
|
||||
let mut net_packet = NetPacket::new(vec![0u8; 4 + 8 + 1500])?;
|
||||
net_packet.set_version(Version::V1);
|
||||
net_packet.set_protocol(Protocol::Ipv4Turn);
|
||||
@@ -109,8 +109,8 @@ fn start_(sender: Sender<Ipv4Addr>,
|
||||
net_packet.set_ttl(MAX_TTL);
|
||||
let mut buf = [0; 4096];
|
||||
loop {
|
||||
let data = tun_reader.read(&mut buf)?;
|
||||
match handle(&sender, data, &tun_writer, current_device.load(), &mut net_packet) {
|
||||
let len = tun_reader.read(&mut buf)?;
|
||||
match handle(&sender, &mut buf[..len], &tun_writer, current_device.load(), &mut net_packet) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e)
|
||||
|
||||
+1
-1
@@ -1,6 +1,5 @@
|
||||
use crate::error::Error;
|
||||
|
||||
|
||||
pub use p2p_channel::channel::{Route, RouteKey};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
@@ -11,4 +10,5 @@ pub mod nat;
|
||||
pub mod proto;
|
||||
pub mod protocol;
|
||||
pub mod tun_device;
|
||||
pub mod tap_device;
|
||||
pub mod core;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use p2p_channel::punch::NatType;
|
||||
use std::collections::HashSet;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
|
||||
use std::time::Duration;
|
||||
use std::{io, thread};
|
||||
use p2p_channel::punch::NatType;
|
||||
|
||||
|
||||
// #[derive(Debug, Copy, Clone, PartialEq)]
|
||||
// pub enum NatType {
|
||||
|
||||
+52
-18
@@ -1,9 +1,9 @@
|
||||
use crate::proto::message::PunchNatType;
|
||||
use p2p_channel::punch::{NatInfo, NatType};
|
||||
use parking_lot::Mutex;
|
||||
use std::io;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use parking_lot::Mutex;
|
||||
use p2p_channel::punch::{NatInfo, NatType};
|
||||
use crate::proto::message::PunchNatType;
|
||||
|
||||
pub mod check;
|
||||
|
||||
@@ -26,7 +26,7 @@ impl From<NatType> for PunchNatType {
|
||||
fn from(value: NatType) -> Self {
|
||||
match value {
|
||||
NatType::Symmetric => PunchNatType::Symmetric,
|
||||
NatType::Cone => PunchNatType::Cone
|
||||
NatType::Cone => PunchNatType::Cone,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,14 +35,26 @@ impl Into<NatType> for PunchNatType {
|
||||
fn into(self) -> NatType {
|
||||
match self {
|
||||
PunchNatType::Symmetric => NatType::Symmetric,
|
||||
PunchNatType::Cone => NatType::Cone
|
||||
PunchNatType::Cone => NatType::Cone,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NatTest {
|
||||
pub fn new(nat_test_server: Vec<SocketAddr>, public_ip: Ipv4Addr, public_port: u16, local_ip: IpAddr, local_port: u16) -> NatTest {
|
||||
let info = NatTest::re_test_(&nat_test_server, public_ip, public_port, local_ip, local_port);
|
||||
pub fn new(
|
||||
nat_test_server: Vec<SocketAddr>,
|
||||
public_ip: Ipv4Addr,
|
||||
public_port: u16,
|
||||
local_ip: IpAddr,
|
||||
local_port: u16,
|
||||
) -> NatTest {
|
||||
let info = NatTest::re_test_(
|
||||
&nat_test_server,
|
||||
public_ip,
|
||||
public_port,
|
||||
local_ip,
|
||||
local_port,
|
||||
);
|
||||
NatTest {
|
||||
nat_test_server: Arc::new(nat_test_server),
|
||||
info: Arc::new(Mutex::new(info)),
|
||||
@@ -51,12 +63,30 @@ impl NatTest {
|
||||
pub fn nat_info(&self) -> NatInfo {
|
||||
self.info.lock().clone()
|
||||
}
|
||||
pub fn re_test(&self, public_ip: Ipv4Addr, public_port: u16, local_ip: IpAddr, local_port: u16) -> NatInfo {
|
||||
let info = NatTest::re_test_(&self.nat_test_server, public_ip, public_port, local_ip, local_port);
|
||||
pub fn re_test(
|
||||
&self,
|
||||
public_ip: Ipv4Addr,
|
||||
public_port: u16,
|
||||
local_ip: IpAddr,
|
||||
local_port: u16,
|
||||
) -> NatInfo {
|
||||
let info = NatTest::re_test_(
|
||||
&self.nat_test_server,
|
||||
public_ip,
|
||||
public_port,
|
||||
local_ip,
|
||||
local_port,
|
||||
);
|
||||
*self.info.lock() = info.clone();
|
||||
info
|
||||
}
|
||||
fn re_test_(nat_test_server: &Vec<SocketAddr>, public_ip: Ipv4Addr, public_port: u16, local_ip: IpAddr, local_port: u16) -> NatInfo {
|
||||
fn re_test_(
|
||||
nat_test_server: &Vec<SocketAddr>,
|
||||
public_ip: Ipv4Addr,
|
||||
public_port: u16,
|
||||
local_ip: IpAddr,
|
||||
local_port: u16,
|
||||
) -> NatInfo {
|
||||
return match check::public_ip_list(nat_test_server) {
|
||||
Ok((nat_type, ips, port_range)) => {
|
||||
let mut public_ips = Vec::new();
|
||||
@@ -66,22 +96,26 @@ impl NatTest {
|
||||
public_ips.push(IpAddr::from(ip));
|
||||
}
|
||||
}
|
||||
NatInfo::new(public_ips,
|
||||
public_port,
|
||||
port_range,
|
||||
local_ip, local_port,
|
||||
nat_type, )
|
||||
NatInfo::new(
|
||||
public_ips,
|
||||
public_port,
|
||||
port_range,
|
||||
local_ip,
|
||||
local_port,
|
||||
nat_type,
|
||||
)
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("{:?}",e);
|
||||
log::warn!("{:?}", e);
|
||||
NatInfo::new(
|
||||
vec![IpAddr::from(public_ip)],
|
||||
public_port,
|
||||
0,
|
||||
local_ip, local_port,
|
||||
local_ip,
|
||||
local_port,
|
||||
NatType::Cone,
|
||||
)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
use std::{fmt, io};
|
||||
|
||||
|
||||
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
|
||||
pub enum Protocol {
|
||||
/// ping请求
|
||||
@@ -107,4 +106,4 @@ impl<B: AsRef<[u8]>> fmt::Debug for PingPacket<B> {
|
||||
.field("epoch", &self.epoch())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+17
-14
@@ -1,19 +1,19 @@
|
||||
use std::{fmt, io};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::{fmt, io};
|
||||
|
||||
/*
|
||||
0 15 31
|
||||
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 版本(8) | 协议(8) | 上层协议(8) | 初始ttl(4) | 生存时间(4) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 源ip地址(32) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 目的ip地址(32) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 数据体 |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
*/
|
||||
0 15 31
|
||||
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 版本(8) | 协议(8) | 上层协议(8) | 初始ttl(4) | 生存时间(4) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 源ip地址(32) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 目的ip地址(32) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 数据体 |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
*/
|
||||
|
||||
pub mod control_packet;
|
||||
pub mod error_packet;
|
||||
@@ -98,7 +98,10 @@ impl<B: AsRef<[u8]>> NetPacket<B> {
|
||||
let len = buffer.as_ref().len();
|
||||
// 不能大于udp最大载荷长度
|
||||
if len < 12 || len > 65535 - 20 - 8 {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "length overflow"));
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"length overflow",
|
||||
));
|
||||
}
|
||||
Ok(NetPacket { buffer })
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
|
||||
pub enum Protocol {
|
||||
Punch,
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
use crate::tun_device::{TunReader, TunWriter};
|
||||
|
||||
pub type TapReader = TunReader;
|
||||
pub type TapWriter = TunWriter;
|
||||
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use tun::Device;
|
||||
use parking_lot::Mutex;
|
||||
use std::io;
|
||||
|
||||
pub fn create_tap(
|
||||
address: Ipv4Addr,
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
) -> io::Result<(TunWriter, TunReader, [u8; 6])> {
|
||||
println!("========TAP网卡配置========");
|
||||
let mut config = tun::Configuration::default();
|
||||
|
||||
config
|
||||
.destination(gateway)
|
||||
.address(address)
|
||||
.netmask(netmask)
|
||||
.mtu(1420)
|
||||
.layer(tun::Layer::L2)
|
||||
// .queues(2) 用多个队列有兼容性问题
|
||||
.up();
|
||||
|
||||
let dev = tun::create(&config).unwrap();
|
||||
let name = dev.name();
|
||||
println!("name:{:?}", name);
|
||||
let packet_information = dev.has_packet_information();
|
||||
let queue = dev.queue(0).unwrap();
|
||||
let reader = queue.reader();
|
||||
let writer = queue.writer();
|
||||
let get_mac_cmd = format!("cat /sys/class/net/{}/address", name);
|
||||
let mac_out = std::process::Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(get_mac_cmd)
|
||||
.output()
|
||||
.expect("sh exec error!");
|
||||
if !mac_out.status.success() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("获取mac地址错误: {:?}", mac_out)));
|
||||
}
|
||||
let mac_str = String::from_utf8(mac_out.stdout).unwrap();
|
||||
let mut mac = [0; 6];
|
||||
let mut split = mac_str.split(":");
|
||||
for i in 0..6 {
|
||||
mac[i] = u8::from_str_radix(&split.next().unwrap()[..2], 16).unwrap();
|
||||
}
|
||||
println!("mac:{:?}", mac);
|
||||
println!("========TAP网卡配置========");
|
||||
Ok((
|
||||
TunWriter(writer, packet_information, Arc::new(Mutex::new(dev))),
|
||||
TunReader(reader, packet_information),
|
||||
mac
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
use crate::tun_device::{TunReader, TunWriter};
|
||||
|
||||
pub type TapReader = TunReader;
|
||||
pub type TapWriter = TunWriter;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub fn create_tap(
|
||||
address: Ipv4Addr,
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
) -> crate::error::Result<(TapWriter, TapReader, [u8; 6])> {
|
||||
unimplemented!()
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows;
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod mac;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use mac::{TapWriter, TapReader};
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use mac::create_tap;
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
pub use linux::{TapWriter, TapReader};
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
pub use linux::create_tap;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows::create_tap;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows::delete_tap;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows::{TapReader, TapWriter};
|
||||
@@ -0,0 +1,100 @@
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use win_tun_tap::{IFace, TapDevice};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TapWriter(Arc<TapDevice>, Arc<Mutex<()>>);
|
||||
|
||||
impl TapWriter {
|
||||
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
|
||||
self.0.write(buf)
|
||||
}
|
||||
|
||||
pub fn change_ip(
|
||||
&self,
|
||||
address: Ipv4Addr,
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
old_netmask: Ipv4Addr,
|
||||
old_gateway: Ipv4Addr,
|
||||
) -> io::Result<()> {
|
||||
if let Err(e) =
|
||||
self.0.delete_route(dest(old_gateway, old_gateway), old_netmask, old_gateway)
|
||||
{
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
self.0.set_ip(address, netmask)?;
|
||||
self.0.add_route(dest(gateway, netmask), netmask, gateway)
|
||||
}
|
||||
pub fn close(&self) -> io::Result<()> {
|
||||
self.0.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
fn dest(ip: Ipv4Addr, mask: Ipv4Addr) -> Ipv4Addr {
|
||||
let ip = ip.octets();
|
||||
let mask = mask.octets();
|
||||
Ipv4Addr::from([
|
||||
ip[0] & mask[0],
|
||||
ip[1] & mask[1],
|
||||
ip[2] & mask[2],
|
||||
ip[3] & mask[3],
|
||||
])
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TapReader(Arc<TapDevice>);
|
||||
|
||||
impl TapReader {
|
||||
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
self.0.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
pub const TAP_INTERFACE_NAME: &str = "Switch-Tap-V1";
|
||||
|
||||
pub fn create_tap(
|
||||
address: Ipv4Addr,
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
) -> io::Result<(TapWriter, TapReader, [u8; 6])> {
|
||||
println!("========TAP网卡配置========");
|
||||
let tap_device = match TapDevice::open(TAP_INTERFACE_NAME) {
|
||||
Ok(tap_device) => tap_device,
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e);
|
||||
let tap_device = TapDevice::create()?;
|
||||
tap_device.set_name(TAP_INTERFACE_NAME)?;
|
||||
tap_device
|
||||
}
|
||||
};
|
||||
let mac = tap_device.get_mac()?;
|
||||
println!("name:{:?}", tap_device.get_name()?);
|
||||
println!("version:{:x?}", tap_device.get_version()?);
|
||||
println!("mac:{:x?}", mac);
|
||||
tap_device.set_ip(address, netmask)?;
|
||||
tap_device.set_mtu(1420)?;
|
||||
tap_device.set_status(true)?;
|
||||
tap_device.add_route(address, netmask, gateway)?;
|
||||
let tap = Arc::new(tap_device);
|
||||
println!("========TAP网卡配置========");
|
||||
Ok((
|
||||
TapWriter(tap.clone(), Arc::default()),
|
||||
TapReader(tap),
|
||||
mac
|
||||
))
|
||||
}
|
||||
|
||||
pub fn delete_tap() {
|
||||
let tap_device = match TapDevice::open(TAP_INTERFACE_NAME) {
|
||||
Ok(tap_device) => tap_device,
|
||||
Err(_) => {
|
||||
return;
|
||||
}
|
||||
};
|
||||
let _ = tap_device.delete();
|
||||
}
|
||||
@@ -9,6 +9,7 @@ pub fn create_tun(
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
) -> crate::error::Result<(TunWriter, TunReader)> {
|
||||
println!("========TUN网卡配置========");
|
||||
let mut config = tun::Configuration::default();
|
||||
|
||||
config
|
||||
@@ -28,6 +29,8 @@ pub fn create_tun(
|
||||
let queue = dev.queue(0).unwrap();
|
||||
let reader = queue.reader();
|
||||
let writer = queue.writer();
|
||||
println!("name:{:?}", dev.name());
|
||||
println!("========TUN网卡配置========");
|
||||
Ok((
|
||||
TunWriter(writer, packet_information, Arc::new(Mutex::new(dev))),
|
||||
TunReader(reader, packet_information),
|
||||
|
||||
@@ -12,6 +12,7 @@ pub fn create_tun(
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
) -> crate::error::Result<(TunWriter, TunReader)> {
|
||||
println!("========TUN网卡配置========");
|
||||
let mut config = tun::Configuration::default();
|
||||
|
||||
config
|
||||
@@ -23,22 +24,13 @@ pub fn create_tun(
|
||||
|
||||
let dev = tun::create(&config).unwrap();
|
||||
config_ip(dev.name(), address, netmask, gateway)?;
|
||||
// println!("{:?}", if_config_out);
|
||||
// let cmd_str: String = " ifconfig|grep flags=8051|awk -F ':' '{print $1}'|tail -1".to_string();
|
||||
//
|
||||
// let cmd_str_out = Command::new("sh")
|
||||
// .arg("-c")
|
||||
// .arg(cmd_str)
|
||||
// .output()
|
||||
// .expect("sh exec error!");
|
||||
// if !cmd_str_out.status.success(){
|
||||
// return Err(Error::Stop(format!("设置路由失败:{:?}", cmd_str_out)));
|
||||
// }
|
||||
// println!("{:?}", cmd_str_out);
|
||||
|
||||
let packet_information = dev.has_packet_information();
|
||||
let queue = dev.queue(0).unwrap();
|
||||
let reader = queue.reader();
|
||||
let writer = queue.writer();
|
||||
println!("name:{:?}", dev.name());
|
||||
println!("========TUN网卡配置========");
|
||||
Ok((
|
||||
TunWriter(writer, packet_information, Arc::new(Mutex::new(dev))),
|
||||
TunReader(reader, packet_information),
|
||||
|
||||
@@ -7,6 +7,8 @@ pub use unix::{TunReader, TunWriter};
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows::create_tun;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows::delete_tun;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub use windows::{TunReader, TunWriter};
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
|
||||
@@ -15,21 +15,8 @@ use parking_lot::Mutex;
|
||||
pub struct TunReader(pub(crate) Reader, pub(crate) bool);
|
||||
|
||||
impl TunReader {
|
||||
pub fn read<'a>(&'a self, buf: &'a mut [u8]) -> io::Result<&mut [u8]> {
|
||||
let len = self.0.read(buf)?;
|
||||
if self.1 {
|
||||
Ok(&mut buf[4..len])
|
||||
} else {
|
||||
Ok(&mut buf[..len])
|
||||
}
|
||||
}
|
||||
pub fn close(&self) {
|
||||
unsafe {
|
||||
let raw = self.0.as_raw_fd();
|
||||
if raw >= 0 {
|
||||
libc::close(raw);
|
||||
}
|
||||
}
|
||||
pub fn read(&self, buf: & mut [u8]) -> io::Result<usize> {
|
||||
self.0.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +39,15 @@ impl TunWriter {
|
||||
self.0.write_all(packet)
|
||||
}
|
||||
}
|
||||
pub fn close(&self) -> io::Result<()>{
|
||||
unsafe {
|
||||
let raw = self.0.as_raw_fd();
|
||||
if raw >= 0 {
|
||||
libc::close(raw);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn change_ip(&self, address: Ipv4Addr, netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr, _old_netmask: Ipv4Addr, _old_gateway: Ipv4Addr) -> io::Result<()> {
|
||||
let mut config = tun::Configuration::default();
|
||||
|
||||
@@ -4,52 +4,62 @@ use std::sync::Arc;
|
||||
|
||||
use libloading::Library;
|
||||
use parking_lot::Mutex;
|
||||
use wintun::{Adapter, Packet, Session};
|
||||
|
||||
pub const INTERFACE_NAME: &str = "Switch-V1";
|
||||
pub const POOL_NAME: &str = "Switch-V1";
|
||||
use win_tun_tap::{IFace, TunDevice};
|
||||
use win_tun_tap::packet::TunPacket;
|
||||
|
||||
pub const TUN_INTERFACE_NAME: &str = "Switch-V1";
|
||||
pub const TUN_POOL_NAME: &str = "Switch-V1";
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TunWriter(Arc<Session>, Arc<Mutex<u32>>);
|
||||
pub struct TunWriter(Arc<TunDevice>, Arc<Mutex<()>>);
|
||||
|
||||
impl TunWriter {
|
||||
pub fn write(&self, buf: &[u8]) -> io::Result<()> {
|
||||
match self.0.allocate_send_packet(buf.len() as u16) {
|
||||
Ok(mut packet) => {
|
||||
packet.bytes_mut().copy_from_slice(buf);
|
||||
self.0.send_packet(packet);
|
||||
return Ok(());
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "send err"));
|
||||
let mut packet = self.0.allocate_send_packet(buf.len() as u16)?;
|
||||
packet.bytes_mut().copy_from_slice(buf);
|
||||
self.0.send_packet(packet);
|
||||
return Ok(());
|
||||
}
|
||||
pub fn change_ip(&self, address: Ipv4Addr, netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr, old_netmask: Ipv4Addr, old_gateway: Ipv4Addr) -> io::Result<()> {
|
||||
let index = self.1.lock();
|
||||
if let Err(e) = delete_route(*index, old_netmask, old_gateway) {
|
||||
log::warn!("{:?}",e);
|
||||
pub fn change_ip(
|
||||
&self,
|
||||
address: Ipv4Addr,
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
old_netmask: Ipv4Addr,
|
||||
old_gateway: Ipv4Addr,
|
||||
) -> io::Result<()> {
|
||||
if let Err(e) =
|
||||
self.0.delete_route(dest(old_gateway, old_gateway), old_netmask, old_gateway)
|
||||
{
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
config_ip(*index, address, netmask, gateway)
|
||||
self.0.set_ip(address, netmask)?;
|
||||
self.0.add_route(dest(gateway, netmask), netmask, gateway)
|
||||
}
|
||||
pub fn close(&self) -> io::Result<()> {
|
||||
self.0.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
fn dest(ip: Ipv4Addr, mask: Ipv4Addr) -> Ipv4Addr {
|
||||
let ip = ip.octets();
|
||||
let mask = mask.octets();
|
||||
Ipv4Addr::from([
|
||||
ip[0] & mask[0],
|
||||
ip[1] & mask[1],
|
||||
ip[2] & mask[2],
|
||||
ip[3] & mask[3],
|
||||
])
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TunReader(pub(crate) Arc<Session>);
|
||||
pub struct TunReader(Arc<TunDevice>);
|
||||
|
||||
|
||||
impl TunReader {
|
||||
pub fn next(&self) -> io::Result<Packet> {
|
||||
match self.0.receive_blocking() {
|
||||
Ok(packet) => {
|
||||
return Ok(packet);
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "read err"));
|
||||
}
|
||||
pub fn close(&self) {
|
||||
self.0.shutdown()
|
||||
pub fn next(&self) -> io::Result<TunPacket> {
|
||||
self.0.receive_blocking()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,158 +68,66 @@ pub fn create_tun(
|
||||
netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr,
|
||||
) -> io::Result<(TunWriter, TunReader)> {
|
||||
let win_tun = unsafe {
|
||||
unsafe {
|
||||
println!("========TUN网卡配置========");
|
||||
match Library::new("wintun.dll") {
|
||||
Ok(library) => match wintun::load_from_library(library) {
|
||||
Ok(win_tun) => win_tun,
|
||||
Err(e) => {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("{:?}", e)));
|
||||
Ok(lib) => match TunDevice::open(lib, TUN_INTERFACE_NAME) {
|
||||
Ok(tun_device) => {
|
||||
let _ = tun_device.delete();
|
||||
}
|
||||
Err(_) => {}
|
||||
},
|
||||
Err(e) => {
|
||||
log::error!("wintun.dll not found");
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("wintun.dll not found {:?}", e)));
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("wintun.dll not found {:?}", e),
|
||||
));
|
||||
}
|
||||
}
|
||||
};
|
||||
if let Ok(adapter) = Adapter::open(&win_tun, INTERFACE_NAME) {
|
||||
log::warn!("Switch-V1 未正常退出");
|
||||
drop(adapter);
|
||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||
};
|
||||
let adapter = match Adapter::create(&win_tun, POOL_NAME, INTERFACE_NAME, None) {
|
||||
Ok(adapter) => adapter,
|
||||
Err(e) => return Err(io::Error::new(io::ErrorKind::Other, format!("{:?}", e))),
|
||||
};
|
||||
let session = Arc::new(adapter.start_session(wintun::MAX_RING_CAPACITY).unwrap());
|
||||
let index = match adapter.get_adapter_index() {
|
||||
Ok(index) => {
|
||||
index
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("get_adapter_index err {:?}",e);
|
||||
get_if_index()
|
||||
}
|
||||
};
|
||||
config_ip(index, address, netmask, gateway)?;
|
||||
let reader_session = session.clone();
|
||||
Ok((TunWriter(session.clone(), Arc::new(Mutex::new(index))), TunReader(reader_session)))
|
||||
let tun_device = match TunDevice::create(
|
||||
Library::new("wintun.dll").unwrap(),
|
||||
TUN_POOL_NAME,
|
||||
TUN_INTERFACE_NAME,
|
||||
) {
|
||||
Ok(tun_device) => tun_device,
|
||||
Err(e) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("{:?}", e),
|
||||
));
|
||||
}
|
||||
};
|
||||
println!("name:{:?}", tun_device.get_name()?);
|
||||
println!("version:{:?}", tun_device.version()?);
|
||||
log::error!("创建tun成功 {:?}",tun_device.get_name()?);
|
||||
tun_device.set_ip(address, netmask)?;
|
||||
tun_device.set_mtu(1420)?;
|
||||
tun_device.add_route(address, netmask, gateway)?;
|
||||
let device = Arc::new(tun_device);
|
||||
println!("========TUN网卡配置========");
|
||||
Ok((
|
||||
TunWriter(device.clone(), Arc::default()),
|
||||
TunReader(device),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_if_index() -> u32 {
|
||||
let cmd = format!("netsh int ipv4 show interfaces {} |findstr IfIndex", INTERFACE_NAME);
|
||||
let out = std::process::Command::new("cmd")
|
||||
.arg("/C")
|
||||
.arg(&cmd)
|
||||
.output()
|
||||
.unwrap();
|
||||
if !out.status.success() {
|
||||
log::warn!("1获取网络接口索引失败:cmd={:?},out={:?}",cmd,out);
|
||||
return 0;
|
||||
}
|
||||
if let Ok(stdout) = String::from_utf8(out.stdout) {
|
||||
if let Some(start) = stdout.find(":") {
|
||||
if let Some(end) = stdout.find("\r\n") {
|
||||
if let Ok(index) = stdout[start + 1..end].trim().parse::<u32>() {
|
||||
return index;
|
||||
pub fn delete_tun() {
|
||||
unsafe {
|
||||
match Library::new("wintun.dll") {
|
||||
Ok(lib) => match TunDevice::open(lib, TUN_INTERFACE_NAME) {
|
||||
Ok(tun_device) => {
|
||||
let _ = tun_device.delete();
|
||||
}
|
||||
}
|
||||
Err(_) => {}
|
||||
},
|
||||
Err(_) => {}
|
||||
}
|
||||
}
|
||||
log::warn!("2获取网络接口索引失败:cmd={:?}",cmd);
|
||||
0
|
||||
}
|
||||
|
||||
fn config_ip(index: u32, address: Ipv4Addr, netmask: Ipv4Addr, gateway: Ipv4Addr) -> io::Result<()> {
|
||||
if index == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("网络接口索引错误: {:?}", index)));
|
||||
}
|
||||
let set_mtu = format!(
|
||||
"netsh interface ipv4 set subinterface {} mtu=1420 store=persistent",
|
||||
index
|
||||
);
|
||||
let set_metric = format!("netsh interface ip set interface {} metric=1", index);
|
||||
let set_address = format!(
|
||||
"netsh interface ip set address {} static {:?} {:?} ", // gateway={:?}
|
||||
index, address, netmask,
|
||||
);
|
||||
// 执行网卡初始化命令
|
||||
let out = std::process::Command::new("cmd")
|
||||
.arg("/C")
|
||||
.arg(set_mtu)
|
||||
.output()
|
||||
.unwrap();
|
||||
if !out.status.success() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("设置mtu失败: {:?}", out)));
|
||||
}
|
||||
let out = std::process::Command::new("cmd")
|
||||
.arg("/C")
|
||||
.arg(set_metric)
|
||||
.output()
|
||||
.unwrap();
|
||||
if !out.status.success() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("设置接口跃点失败: {:?}", out)));
|
||||
}
|
||||
let out = std::process::Command::new("cmd")
|
||||
.arg("/C")
|
||||
.arg(&set_address)
|
||||
.output()
|
||||
.unwrap();
|
||||
if !out.status.success() {
|
||||
log::error!("cmd={:?},out={:?}",set_address,out);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("设置网络地址失败: {:?}", out)));
|
||||
}
|
||||
let dest = {
|
||||
let ip = address.octets();
|
||||
let mask = netmask.octets();
|
||||
Ipv4Addr::from([
|
||||
ip[0] & mask[0],
|
||||
ip[1] & mask[1],
|
||||
ip[2] & mask[2],
|
||||
ip[3] & mask[3],
|
||||
])
|
||||
};
|
||||
let set_route = format!(
|
||||
"route add {:?} mask {:?} {:?} if {}",
|
||||
dest, netmask, gateway, index
|
||||
);
|
||||
// 执行添加路由命令
|
||||
let out = std::process::Command::new("cmd")
|
||||
.arg("/C")
|
||||
.arg(&set_route)
|
||||
.output()
|
||||
.unwrap();
|
||||
if !out.status.success() {
|
||||
log::error!("cmd={:?},out={:?}",set_route,out);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("添加路由失败: {:?}", out)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_route(index: u32, netmask: Ipv4Addr, gateway: Ipv4Addr) -> io::Result<()> {
|
||||
if index == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("网络接口索引错误: {:?}", index)));
|
||||
}
|
||||
let mask = netmask.octets();
|
||||
let ip = gateway.octets();
|
||||
let dest = Ipv4Addr::from([
|
||||
ip[0] & mask[0],
|
||||
ip[1] & mask[1],
|
||||
ip[2] & mask[2],
|
||||
ip[3] & mask[3],
|
||||
]);
|
||||
let delete_route = format!(
|
||||
"route delete {:?} mask {:?} {:?} if {}",
|
||||
dest, netmask, gateway, index
|
||||
);
|
||||
// 删除路由
|
||||
let out = std::process::Command::new("cmd")
|
||||
.arg("/C")
|
||||
.arg(delete_route)
|
||||
.output()
|
||||
.unwrap();
|
||||
if !out.status.success() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("删除路由失败: {:?}", out)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user