v1.1
This commit is contained in:
@@ -4,9 +4,9 @@ use std::sync::Arc;
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use crossbeam_skiplist::SkipMap;
|
||||
use parking_lot::Mutex;
|
||||
use nat_traversal::boot::Boot;
|
||||
use nat_traversal::channel::{Channel, Route, RouteKey};
|
||||
use nat_traversal::punch::NatInfo;
|
||||
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::nat::NatTest;
|
||||
use crate::tun_device;
|
||||
@@ -28,7 +28,7 @@ pub struct Switch {
|
||||
|
||||
impl Switch {
|
||||
pub fn start(config: Config) -> crate::Result<Switch> {
|
||||
let (mut channel, punch, idle) = Boot::new::<Ipv4Addr>(100, 9000, 0)?;
|
||||
let (mut channel, punch, idle) = Boot::new::<Ipv4Addr>(80, 15000, 0)?;
|
||||
let response = registration_handler::registration(&mut channel, config.server_address, config.token.clone(), config.device_id.clone(), config.name.clone())?;
|
||||
let register = Arc::new(registration_handler::Register::new(channel.sender()?, config.server_address, config.token.clone(), config.device_id.clone(), config.name.clone()));
|
||||
let device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>> = Arc::new(Mutex::new((0, Vec::new())));
|
||||
@@ -109,7 +109,7 @@ impl Switch {
|
||||
self.nat_channel.route_to_id(route_key)
|
||||
}
|
||||
pub fn route_table(&self) -> Vec<(Ipv4Addr, Route)> {
|
||||
self.nat_channel.route_list()
|
||||
self.nat_channel.route_table()
|
||||
}
|
||||
pub fn stop(&self) -> io::Result<()> {
|
||||
self.tun_reader.close();
|
||||
|
||||
@@ -7,10 +7,10 @@ use chrono::Local;
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use rand::prelude::SliceRandom;
|
||||
use nat_traversal::channel::Route;
|
||||
|
||||
use nat_traversal::channel::sender::Sender;
|
||||
use nat_traversal::idle::Idle;
|
||||
use p2p_channel::channel::Route;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
use p2p_channel::idle::Idle;
|
||||
|
||||
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
|
||||
use crate::protocol::{control_packet, MAX_TTL, NetPacket, Protocol, Version};
|
||||
@@ -26,9 +26,11 @@ pub fn start_idle(idle: Idle<Ipv4Addr>, sender: Sender<Ipv4Addr>) {
|
||||
|
||||
fn start_idle_(idle: Idle<Ipv4Addr>, sender: Sender<Ipv4Addr>) -> io::Result<()> {
|
||||
loop {
|
||||
let (idle_status, peer_ip, route) = idle.next_idle()?;
|
||||
log::warn!("peer_ip:{:?},route:{:?},idle_status:{:?}",peer_ip,route,idle_status);
|
||||
sender.remove_route(&peer_ip);
|
||||
let (idle_status, peer_ips, route) = idle.next_idle()?;
|
||||
log::warn!("peer_ip:{:?},route:{:?},idle_status:{:?}",peer_ips,route,idle_status);
|
||||
for peer_ip in peer_ips {
|
||||
sender.remove_route(&peer_ip);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,7 +70,7 @@ fn start_heartbeat_(sender: Sender<Ipv4Addr>, device_list: Arc<Mutex<(u16, Vec<P
|
||||
let _ = sender.send_to_addr(net_packet.buffer(), current_device.connect_server);
|
||||
//再随机发送到其他地址,看有没有客户端符合转发条件
|
||||
let route_list = route_list.get_or_insert_with(|| {
|
||||
let mut l = sender.route_list();
|
||||
let mut l = sender.route_table();
|
||||
l.shuffle(&mut rand::thread_rng());
|
||||
l
|
||||
});
|
||||
@@ -84,21 +86,23 @@ fn start_heartbeat_(sender: Sender<Ipv4Addr>, device_list: Arc<Mutex<(u16, Vec<P
|
||||
}
|
||||
}
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
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);
|
||||
}
|
||||
} else {
|
||||
for (peer_ip, route) in sender.route_list().iter() {
|
||||
for (peer_ip, route) in sender.route_table().iter() {
|
||||
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);
|
||||
}
|
||||
thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
|
||||
count += 1;
|
||||
thread::sleep(Duration::from_secs(5));
|
||||
thread::sleep(Duration::from_millis(5000));
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,8 @@ use crossbeam::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use protobuf::Message;
|
||||
use rand::prelude::SliceRandom;
|
||||
use nat_traversal::channel::sender::Sender;
|
||||
use nat_traversal::punch::{NatInfo, NatType, Punch};
|
||||
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};
|
||||
|
||||
@@ -8,8 +8,8 @@ use crossbeam_skiplist::SkipMap;
|
||||
use parking_lot::Mutex;
|
||||
use protobuf::Message;
|
||||
|
||||
use nat_traversal::channel::{Channel, Route, RouteKey};
|
||||
use nat_traversal::punch::NatInfo;
|
||||
use p2p_channel::channel::{Channel, Route, RouteKey};
|
||||
use p2p_channel::punch::NatInfo;
|
||||
use packet::icmp::{icmp, Kind};
|
||||
use packet::ip::ipv4;
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
@@ -221,7 +221,7 @@ impl RecvHandler {
|
||||
})
|
||||
.collect();
|
||||
let mut dev = self.device_list.lock();
|
||||
if dev.0 < device_list_t.epoch as u16 || device_list_t.epoch as u16 - dev.0 > u16::MAX >> 2 {
|
||||
if dev.0 != device_list_t.epoch as u16 {
|
||||
dev.0 = device_list_t.epoch as u16;
|
||||
dev.1 = ip_list;
|
||||
}
|
||||
@@ -357,7 +357,7 @@ impl RecvHandler {
|
||||
net_packet.set_source(current_device.virtual_ip());
|
||||
net_packet.set_destination(source);
|
||||
net_packet.set_payload(&bytes);
|
||||
if !peer_nat_info.local_ip.is_unspecified() {
|
||||
if !peer_nat_info.local_ip.is_unspecified() && peer_nat_info.local_port != 0 {
|
||||
let mut packet = NetPacket::new([0u8; 12])?;
|
||||
packet.set_version(Version::V1);
|
||||
packet.first_set_ttl(1);
|
||||
|
||||
@@ -5,8 +5,8 @@ use std::time::Duration;
|
||||
|
||||
use chrono::Local;
|
||||
use protobuf::Message;
|
||||
use nat_traversal::channel::Channel;
|
||||
use nat_traversal::channel::sender::Sender;
|
||||
use p2p_channel::channel::Channel;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
|
||||
use crate::error::*;
|
||||
use crate::proto::message::{RegistrationRequest, RegistrationResponse};
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
|
||||
use nat_traversal::channel::sender::Sender;
|
||||
use p2p_channel::channel::sender::Sender;
|
||||
use packet::icmp::icmp::IcmpPacket;
|
||||
use packet::icmp::Kind;
|
||||
use packet::ip::ipv4;
|
||||
@@ -59,8 +59,8 @@ fn handle(sender: &Sender<Ipv4Addr>, data: &mut [u8], tun_writer: &TunWriter, cu
|
||||
net_packet.set_destination(dest_ip);
|
||||
net_packet.set_payload(ipv4_packet.buffer);
|
||||
//优先发到直连到地址
|
||||
if sender.send_to_id(&net_packet.buffer()[..(4 + 8 + data_len)], &dest_ip).is_err() {
|
||||
sender.send_to_addr(&net_packet.buffer()[..(4 + 8 + data_len)], current_device.connect_server)?;
|
||||
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)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
@@ -76,6 +76,7 @@ pub fn start(sender: Sender<Ipv4Addr>,
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn start_(sender: Sender<Ipv4Addr>,
|
||||
tun_reader: TunReader,
|
||||
tun_writer: TunWriter,
|
||||
@@ -94,4 +95,26 @@ fn start_(sender: Sender<Ipv4Addr>,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux",target_os = "macos"))]
|
||||
fn start_(sender: Sender<Ipv4Addr>,
|
||||
tun_reader: TunReader,
|
||||
tun_writer: TunWriter,
|
||||
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);
|
||||
net_packet.set_transport_protocol(ipv4::protocol::Protocol::Ipv4.into());
|
||||
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) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-356
@@ -1,25 +1,7 @@
|
||||
use crate::error::Error;
|
||||
|
||||
// use std::io;
|
||||
// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
|
||||
// use std::sync::atomic::Ordering;
|
||||
// use std::sync::Arc;
|
||||
// use std::time::Duration;
|
||||
//
|
||||
// use crossbeam::atomic::AtomicCell;
|
||||
// use crossbeam::sync::WaitGroup;
|
||||
// use parking_lot::Mutex;
|
||||
// use tokio::sync::watch;
|
||||
//
|
||||
// use error::*;
|
||||
//
|
||||
// use crate::handle::registration_handler::CONNECTION_STATUS;
|
||||
// use crate::handle::{
|
||||
// ApplicationStatus, ConnectStatus, CurrentDeviceInfo, NatInfo, PeerDeviceInfo, Route, RouteType,
|
||||
// DEVICE_LIST, DIRECT_ROUTE_TABLE, NAT_INFO, SERVER_RT,
|
||||
// };
|
||||
// use crate::nat::channel::NatChannel;
|
||||
pub use nat_traversal::channel::{Route, RouteKey};
|
||||
|
||||
pub use p2p_channel::channel::{Route, RouteKey};
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
@@ -30,339 +12,3 @@ pub mod proto;
|
||||
pub mod protocol;
|
||||
pub mod tun_device;
|
||||
pub mod core;
|
||||
|
||||
//
|
||||
// #[derive(Clone, Debug)]
|
||||
// pub struct Config<F> {
|
||||
// pub token: String,
|
||||
// pub mac_address: String,
|
||||
// pub name: String,
|
||||
// pub server_address: SocketAddr,
|
||||
// pub nat_test_server: Vec<SocketAddr>,
|
||||
// pub abnormal_call: F,
|
||||
// }
|
||||
//
|
||||
// impl<F> Config<F> {
|
||||
// pub fn new(
|
||||
// token: String,
|
||||
// mac_address: String,
|
||||
// name: Option<String>,
|
||||
// server_address: SocketAddr,
|
||||
// nat_test_server: Vec<SocketAddr>,
|
||||
// abnormal_call: F,
|
||||
// ) -> Result<Self>
|
||||
// where
|
||||
// F: FnOnce() + Send + 'static,
|
||||
// {
|
||||
// if token.is_empty() || token.len() > 64 {
|
||||
// return Err(Error::Stop("token invalid".to_string()));
|
||||
// }
|
||||
// if mac_address.len() != 12 + 5 {
|
||||
// return Err(Error::Stop("mac_address invalid".to_string()));
|
||||
// }
|
||||
// if let Some(name) = name {
|
||||
// if name.is_empty() || name.len() > 64 {
|
||||
// return Err(Error::Stop("name invalid".to_string()));
|
||||
// }
|
||||
// Ok(Self {
|
||||
// token,
|
||||
// mac_address,
|
||||
// name,
|
||||
// server_address,
|
||||
// nat_test_server,
|
||||
// abnormal_call,
|
||||
// })
|
||||
// } else {
|
||||
// let info = os_info::get();
|
||||
// let name = if info.version() != &os_info::Version::Unknown {
|
||||
// format!("{} {}", info.os_type(), info.version())
|
||||
// } else {
|
||||
// format!("{}", info.os_type())
|
||||
// };
|
||||
// Ok(Self {
|
||||
// token,
|
||||
// mac_address,
|
||||
// name,
|
||||
// server_address,
|
||||
// nat_test_server,
|
||||
// abnormal_call,
|
||||
// })
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// pub struct Switch {
|
||||
// current_device: CurrentDeviceInfo,
|
||||
// status_sender: Arc<Mutex<watch::Sender<ApplicationStatus>>>,
|
||||
// wait_group: WaitGroup,
|
||||
// runtime: Option<tokio::runtime::Runtime>,
|
||||
// }
|
||||
//
|
||||
// impl Switch {
|
||||
// pub fn start<F>(config: Config<F>) -> Result<Self>
|
||||
// where
|
||||
// F: FnOnce() + Send + 'static,
|
||||
// {
|
||||
// let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
// .enable_all()
|
||||
// .build()
|
||||
// .unwrap();
|
||||
// todo!()
|
||||
// // return match runtime.block_on(Switch::start_(config)) {
|
||||
// // Ok(mut switch) => {
|
||||
// // switch.runtime = Some(runtime);
|
||||
// // Ok(switch)
|
||||
// // }
|
||||
// // Err(e) => Err(e),
|
||||
// // };
|
||||
// }
|
||||
// pub fn stop(self) {
|
||||
// Self::call_stop(self.status_sender);
|
||||
// self.wait_group.wait();
|
||||
// }
|
||||
// pub fn stop_async(&self) {
|
||||
// Self::call_stop(self.status_sender.clone());
|
||||
// }
|
||||
// pub fn current_device(&self) -> &CurrentDeviceInfo {
|
||||
// &self.current_device
|
||||
// }
|
||||
// pub fn nat_info(&self) -> Option<NatInfo> {
|
||||
// NAT_INFO.lock().clone()
|
||||
// }
|
||||
// pub fn server_rt(&self) -> i64 {
|
||||
// SERVER_RT.load(Ordering::Relaxed)
|
||||
// }
|
||||
// pub fn connection_status(&self) -> ConnectStatus {
|
||||
// CONNECTION_STATUS.load()
|
||||
// }
|
||||
// pub fn device_list(&self) -> Vec<PeerDeviceInfo> {
|
||||
// let device_list_lock = DEVICE_LIST.lock();
|
||||
// let (_epoch, device_list) = device_list_lock.clone();
|
||||
// drop(device_list_lock);
|
||||
// device_list
|
||||
// }
|
||||
// pub fn route(&self, ip: &Ipv4Addr) -> Route {
|
||||
// if let Some(route_ref) = DIRECT_ROUTE_TABLE.get(ip) {
|
||||
// route_ref.value().clone()
|
||||
// } else {
|
||||
// let mut route = Route::new(self.current_device.connect_server);
|
||||
// route.route_type = RouteType::ServerRelay;
|
||||
// route.rt = self.server_rt() * 2;
|
||||
// route.recv_time = -1;
|
||||
// route
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// impl Switch {
|
||||
// fn call_stop(status_sender: Arc<Mutex<watch::Sender<ApplicationStatus>>>) -> bool {
|
||||
// let lock = status_sender.lock();
|
||||
// let status = lock.send_replace(ApplicationStatus::Stopping);
|
||||
// return status == ApplicationStatus::Starting;
|
||||
// }
|
||||
// // pub async fn start_<F>(config: Config<F>) -> Result<Self>
|
||||
// // where
|
||||
// // F: FnOnce() + Send + 'static,
|
||||
// // {
|
||||
// // // let server_address = "nat1.wherewego.top:29876"
|
||||
// // // let server_address = "nat1.wherewego.top:29875".to_socket_addrs().unwrap().next().unwrap();
|
||||
// // let server_address = config.server_address;
|
||||
// // let nat_channel = NatChannel::new(server_address,100,).await?;
|
||||
// // //注册
|
||||
// // let response = handle::registration_handler::registration(
|
||||
// // &udp,
|
||||
// // server_address,
|
||||
// // config.token,
|
||||
// // config.mac_address,
|
||||
// // config.name,
|
||||
// // )?;
|
||||
// // {
|
||||
// // let ip_list = response
|
||||
// // .device_info_list
|
||||
// // .into_iter()
|
||||
// // .map(|info| {
|
||||
// // PeerDeviceInfo::new(
|
||||
// // Ipv4Addr::from(info.virtual_ip),
|
||||
// // info.name,
|
||||
// // info.device_status as u8,
|
||||
// // )
|
||||
// // })
|
||||
// // .collect();
|
||||
// // let mut dev = DEVICE_LIST.lock();
|
||||
// // dev.0 = response.epoch;
|
||||
// // dev.1 = ip_list;
|
||||
// // }
|
||||
// // 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 (status_sender, status_receiver) = watch::channel(ApplicationStatus::Starting);
|
||||
// // let current_device =
|
||||
// // CurrentDeviceInfo::new(virtual_ip, virtual_gateway, virtual_netmask, server_address);
|
||||
// // let wait_group = WaitGroup::new();
|
||||
// // let status_sender = Arc::new(parking_lot::const_mutex(status_sender));
|
||||
// // let call = Arc::new(AtomicCell::new(Some(config.abnormal_call)));
|
||||
// // //心跳线程
|
||||
// // {
|
||||
// // let udp = udp.try_clone()?;
|
||||
// // let wait_group1 = wait_group.clone();
|
||||
// // let status_sender1 = status_sender.clone();
|
||||
// // let call1 = call.clone();
|
||||
// // handle::heartbeat_handler::start(
|
||||
// // status_receiver.clone(),
|
||||
// // udp,
|
||||
// // current_device,
|
||||
// // move || {
|
||||
// // if Self::call_stop(status_sender1) {
|
||||
// // if let Some(call) = call1.take() {
|
||||
// // call();
|
||||
// // }
|
||||
// // }
|
||||
// // drop(wait_group1);
|
||||
// // },
|
||||
// // )
|
||||
// // .await;
|
||||
// // }
|
||||
// // //初始化nat数据
|
||||
// // handle::init_nat_test_addr(config.nat_test_server);
|
||||
// // handle::init_nat_info(response.public_ip, response.public_port as u16);
|
||||
// // // tun服务
|
||||
// // let (tun_writer, tun_reader) =
|
||||
// // tun_device::create_tun(virtual_ip, virtual_netmask, virtual_gateway)?;
|
||||
// // // 打洞数据通道
|
||||
// // let (punch_sender, cone_receiver, req_symmetric_receiver, res_symmetric_receiver) =
|
||||
// // handle::punch_handler::bounded();
|
||||
// // //udp数据处理
|
||||
// // {
|
||||
// // // 低优先级的udp数据通道
|
||||
// // let (sender, receiver) = tokio::sync::mpsc::channel(50);
|
||||
// // let udp1 = udp.try_clone()?;
|
||||
// // let wait_group1 = wait_group.clone();
|
||||
// // let status_sender1 = status_sender.clone();
|
||||
// // let call1 = call.clone();
|
||||
// // handle::udp_recv_handler::udp_recv_start(
|
||||
// // status_receiver.clone(),
|
||||
// // udp1,
|
||||
// // server_address,
|
||||
// // sender,
|
||||
// // tun_writer,
|
||||
// // current_device,
|
||||
// // move || {
|
||||
// // if Self::call_stop(status_sender1) {
|
||||
// // if let Some(call) = call1.take() {
|
||||
// // call();
|
||||
// // }
|
||||
// // }
|
||||
// // drop(wait_group1);
|
||||
// // },
|
||||
// // )
|
||||
// // .await;
|
||||
// // let udp1 = udp.try_clone()?;
|
||||
// // let wait_group1 = wait_group.clone();
|
||||
// // let status_sender1 = status_sender.clone();
|
||||
// // let call1 = call.clone();
|
||||
// // handle::udp_recv_handler::udp_other_recv_start(
|
||||
// // status_receiver.clone(),
|
||||
// // udp1,
|
||||
// // receiver,
|
||||
// // current_device,
|
||||
// // punch_sender,
|
||||
// // move || {
|
||||
// // if Self::call_stop(status_sender1) {
|
||||
// // if let Some(call) = call1.take() {
|
||||
// // call();
|
||||
// // }
|
||||
// // }
|
||||
// // drop(wait_group1);
|
||||
// // },
|
||||
// // )
|
||||
// // .await;
|
||||
// // }
|
||||
// // //打洞处理
|
||||
// // {
|
||||
// // let udp1 = udp.try_clone()?;
|
||||
// // let wait_group1 = wait_group.clone();
|
||||
// // let status_sender1 = status_sender.clone();
|
||||
// // let call1 = call.clone();
|
||||
// // handle::punch_handler::cone_handler_start(
|
||||
// // status_receiver.clone(),
|
||||
// // cone_receiver,
|
||||
// // udp1,
|
||||
// // current_device,
|
||||
// // move || {
|
||||
// // if Self::call_stop(status_sender1) {
|
||||
// // if let Some(call) = call1.take() {
|
||||
// // call();
|
||||
// // }
|
||||
// // }
|
||||
// // drop(wait_group1);
|
||||
// // },
|
||||
// // )
|
||||
// // .await;
|
||||
// // let udp1 = udp.try_clone()?;
|
||||
// // let wait_group1 = wait_group.clone();
|
||||
// // let status_sender1 = status_sender.clone();
|
||||
// // let call1 = call.clone();
|
||||
// // handle::punch_handler::req_symmetric_handler_start(
|
||||
// // status_receiver.clone(),
|
||||
// // req_symmetric_receiver,
|
||||
// // udp1,
|
||||
// // current_device,
|
||||
// // move || {
|
||||
// // if Self::call_stop(status_sender1) {
|
||||
// // if let Some(call) = call1.take() {
|
||||
// // call();
|
||||
// // }
|
||||
// // }
|
||||
// // drop(wait_group1);
|
||||
// // },
|
||||
// // )
|
||||
// // .await;
|
||||
// // let udp1 = udp.try_clone()?;
|
||||
// // let wait_group1 = wait_group.clone();
|
||||
// // let status_sender1 = status_sender.clone();
|
||||
// // let call1 = call.clone();
|
||||
// // handle::punch_handler::res_symmetric_handler_start(
|
||||
// // status_receiver.clone(),
|
||||
// // res_symmetric_receiver,
|
||||
// // udp1,
|
||||
// // current_device,
|
||||
// // move || {
|
||||
// // if Self::call_stop(status_sender1) {
|
||||
// // if let Some(call) = call1.take() {
|
||||
// // call();
|
||||
// // }
|
||||
// // }
|
||||
// // drop(wait_group1);
|
||||
// // },
|
||||
// // )
|
||||
// // .await;
|
||||
// // }
|
||||
// // //tun数据处理
|
||||
// // {
|
||||
// // let wait_group1 = wait_group.clone();
|
||||
// // let status_sender1 = status_sender.clone();
|
||||
// // let call1 = call.clone();
|
||||
// // handle::tun_handler::handler_start(
|
||||
// // status_receiver.clone(),
|
||||
// // udp,
|
||||
// // tun_reader,
|
||||
// // current_device,
|
||||
// // move || {
|
||||
// // if Self::call_stop(status_sender1) {
|
||||
// // if let Some(call) = call1.take() {
|
||||
// // call();
|
||||
// // }
|
||||
// // }
|
||||
// // drop(wait_group1);
|
||||
// // },
|
||||
// // )
|
||||
// // .await;
|
||||
// // }
|
||||
// // Ok(Switch {
|
||||
// // current_device,
|
||||
// // status_sender,
|
||||
// // wait_group,
|
||||
// // runtime: None,
|
||||
// // })
|
||||
// // }
|
||||
// }
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::collections::HashSet;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
|
||||
use std::time::Duration;
|
||||
use std::{io, thread};
|
||||
use nat_traversal::punch::NatType;
|
||||
use p2p_channel::punch::NatType;
|
||||
|
||||
|
||||
// #[derive(Debug, Copy, Clone, PartialEq)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use parking_lot::Mutex;
|
||||
use nat_traversal::punch::{NatInfo, NatType};
|
||||
use p2p_channel::punch::{NatInfo, NatType};
|
||||
use crate::proto::message::PunchNatType;
|
||||
|
||||
pub mod check;
|
||||
|
||||
@@ -86,6 +86,7 @@ impl Into<u8> for Protocol {
|
||||
}
|
||||
|
||||
pub const MAX_TTL: u8 = 0b1111;
|
||||
pub const MAX_SOURCE: u8 = 0b11110000;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
pub struct NetPacket<B> {
|
||||
@@ -152,10 +153,10 @@ impl<B: AsRef<[u8]> + AsMut<[u8]>> NetPacket<B> {
|
||||
self.buffer.as_mut()[3] = ttl << 4 | ttl;
|
||||
}
|
||||
pub fn set_ttl(&mut self, ttl: u8) {
|
||||
self.buffer.as_mut()[3] = MAX_TTL & ttl;
|
||||
self.buffer.as_mut()[3] = (self.buffer.as_mut()[3] & MAX_SOURCE) | (MAX_TTL & ttl);
|
||||
}
|
||||
pub fn set_source_ttl(&mut self, source_ttl: u8) {
|
||||
self.buffer.as_mut()[3] = (source_ttl << 4) | self.buffer.as_ref()[3];
|
||||
self.buffer.as_mut()[3] = (source_ttl << 4) | (MAX_TTL & self.buffer.as_ref()[3]);
|
||||
}
|
||||
pub fn set_source(&mut self, source: Ipv4Addr) {
|
||||
self.buffer.as_mut()[4..8].copy_from_slice(&source.octets());
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use crate::tun_device::{TunReader, TunWriter};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use tun::Device;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
pub fn create_tun(
|
||||
address: Ipv4Addr,
|
||||
@@ -13,17 +16,20 @@ pub fn create_tun(
|
||||
.address(address)
|
||||
.netmask(netmask)
|
||||
.mtu(1420)
|
||||
// .queues(2)
|
||||
.up();
|
||||
//
|
||||
// config.platform(|config| {
|
||||
// config.packet_information(true);
|
||||
// });
|
||||
|
||||
config.platform(|config| {
|
||||
config.packet_information(true);
|
||||
});
|
||||
|
||||
let mut dev = tun::create(&config).unwrap();
|
||||
let dev = tun::create(&config).unwrap();
|
||||
let packet_information = dev.has_packet_information();
|
||||
let (reader, writer) = dev.split();
|
||||
let queue = dev.queue(0).unwrap();
|
||||
let reader = queue.reader();
|
||||
let writer = queue.writer();
|
||||
Ok((
|
||||
TunWriter(writer, packet_information),
|
||||
TunWriter(writer, packet_information, Arc::new(Mutex::new(dev))),
|
||||
TunReader(reader, packet_information),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use std::process::Command;
|
||||
|
||||
use std::io;
|
||||
use tun::Device;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::tun_device::{TunReader, TunWriter};
|
||||
|
||||
@@ -20,33 +22,7 @@ pub fn create_tun(
|
||||
.up();
|
||||
|
||||
let dev = tun::create(&config).unwrap();
|
||||
let up_eth_str: String = format!("ifconfig {} {:?} {:?} up ", dev.name(), address, gateway);
|
||||
let route_add_str: String = format!(
|
||||
"sudo route -n add -net {:?} -netmask {:?} {:?}",
|
||||
address, netmask, gateway
|
||||
);
|
||||
let up_eth_out = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(up_eth_str)
|
||||
.output()
|
||||
.expect("sh exec error!");
|
||||
if !up_eth_out.status.success() {
|
||||
return Err(crate::error::Error::Stop(format!(
|
||||
"设置地址失败:{:?}",
|
||||
up_eth_out
|
||||
)));
|
||||
}
|
||||
let if_config_out = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(route_add_str)
|
||||
.output()
|
||||
.expect("sh exec error!");
|
||||
if !if_config_out.status.success() {
|
||||
return Err(crate::error::Error::Stop(format!(
|
||||
"设置路由失败:{:?}",
|
||||
if_config_out
|
||||
)));
|
||||
}
|
||||
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();
|
||||
//
|
||||
@@ -60,9 +36,36 @@ pub fn create_tun(
|
||||
// }
|
||||
// println!("{:?}", cmd_str_out);
|
||||
let packet_information = dev.has_packet_information();
|
||||
let (reader, writer) = dev.split();
|
||||
let queue = dev.queue(0).unwrap();
|
||||
let reader = queue.reader();
|
||||
let writer = queue.writer();
|
||||
Ok((
|
||||
TunWriter(writer, packet_information),
|
||||
TunWriter(writer, packet_information, Arc::new(Mutex::new(dev))),
|
||||
TunReader(reader, packet_information),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn config_ip(name: &str, address: Ipv4Addr, netmask: Ipv4Addr, gateway: Ipv4Addr) -> io::Result<()> {
|
||||
let up_eth_str: String = format!("ifconfig {} {:?} {:?} up ", name, address, gateway);
|
||||
let route_add_str: String = format!(
|
||||
"sudo route -n add -net {:?} -netmask {:?} {:?}",
|
||||
address, netmask, gateway
|
||||
);
|
||||
let up_eth_out = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(up_eth_str)
|
||||
.output()
|
||||
.expect("sh exec error!");
|
||||
if !up_eth_out.status.success() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("设置网络地址失败: {:?}", up_eth_out)));
|
||||
}
|
||||
let if_config_out = Command::new("sh")
|
||||
.arg("-c")
|
||||
.arg(route_add_str)
|
||||
.output()
|
||||
.expect("sh exec error!");
|
||||
if !if_config_out.status.success() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("添加路由失败: {:?}", if_config_out)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
use std::io;
|
||||
use std::io::{Read, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use bytes::BufMut;
|
||||
use tun::platform::posix::{Reader, Writer};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::os::unix::io::AsRawFd;
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
use tun::platform::linux::Device;
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
use tun::platform::macos::Device;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TunReader(pub(crate) Reader, pub(crate) bool);
|
||||
|
||||
impl TunReader {
|
||||
pub fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> io::Result<&mut [u8]> {
|
||||
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])
|
||||
@@ -15,12 +23,22 @@ impl TunReader {
|
||||
Ok(&mut buf[..len])
|
||||
}
|
||||
}
|
||||
pub fn close(&self) {
|
||||
unsafe {
|
||||
let raw = self.0.as_raw_fd();
|
||||
if raw >= 0 {
|
||||
libc::close(raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TunWriter(pub(crate) Writer, pub(crate) bool);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TunWriter(pub(crate) Writer, pub(crate) bool, pub(crate) Arc<Mutex<Device>>);
|
||||
|
||||
impl TunWriter {
|
||||
pub fn write(&mut self, packet: &[u8]) -> io::Result<()> {
|
||||
pub fn write(&self, packet: &[u8]) -> io::Result<()> {
|
||||
if self.1 {
|
||||
let mut buf = Vec::<u8>::with_capacity(4 + packet.len());
|
||||
buf.put_u16(0);
|
||||
@@ -34,4 +52,23 @@ impl TunWriter {
|
||||
self.0.write_all(packet)
|
||||
}
|
||||
}
|
||||
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();
|
||||
use tun::Device;
|
||||
config
|
||||
.destination(gateway)
|
||||
.address(address)
|
||||
.netmask(netmask)
|
||||
.mtu(1420)
|
||||
// .queues(2)
|
||||
.up();
|
||||
let mut dev = self.2.lock();
|
||||
if let Err(e) = dev.configure(&config) {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("{:?}", e)));
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::tun_device::mac::config_ip(dev.name(), address, netmask, gateway);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,11 @@ use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use libloading::Library;
|
||||
use parking_lot::Mutex;
|
||||
use wintun::{Adapter, Packet, Session};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TunWriter(Arc<Session>, u32);
|
||||
pub struct TunWriter(Arc<Session>, Arc<Mutex<u32>>);
|
||||
|
||||
impl TunWriter {
|
||||
pub fn write(&self, buf: &[u8]) -> io::Result<()> {
|
||||
@@ -22,10 +23,11 @@ impl TunWriter {
|
||||
}
|
||||
pub fn change_ip(&self, address: Ipv4Addr, netmask: Ipv4Addr,
|
||||
gateway: Ipv4Addr, old_netmask: Ipv4Addr, old_gateway: Ipv4Addr) -> io::Result<()> {
|
||||
if let Err(e) = delete_route(self.1, old_netmask, old_gateway) {
|
||||
let index = self.1.lock();
|
||||
if let Err(e) = delete_route(*index, old_netmask, old_gateway) {
|
||||
log::warn!("{:?}",e);
|
||||
}
|
||||
config_ip(self.1, address, netmask, gateway)
|
||||
config_ip(*index, address, netmask, gateway)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,7 +81,7 @@ pub fn create_tun(
|
||||
config_ip(index, address, netmask, gateway)?;
|
||||
let session = Arc::new(adapter.start_session(wintun::MAX_RING_CAPACITY).unwrap());
|
||||
let reader_session = session.clone();
|
||||
Ok((TunWriter(session.clone(), index), TunReader(reader_session)))
|
||||
Ok((TunWriter(session.clone(), Arc::new(Mutex::new(index))), TunReader(reader_session)))
|
||||
}
|
||||
|
||||
fn config_ip(index: u32, address: Ipv4Addr, netmask: Ipv4Addr, gateway: Ipv4Addr) -> io::Result<()> {
|
||||
|
||||
Reference in New Issue
Block a user