完善配置
This commit is contained in:
@@ -31,6 +31,7 @@ lazy_static! {
|
||||
.time_to_idle(Duration::from_secs(60*5)).build();
|
||||
/// 当前设备的nat信息
|
||||
pub static ref NAT_INFO:Mutex<Option<NatInfo>> = const_mutex(None);
|
||||
static ref NAT_TEST_ADDRESS:Mutex<Vec<SocketAddr>> = const_mutex(Vec::new());
|
||||
}
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct PeerDeviceInfo {
|
||||
@@ -96,10 +97,10 @@ impl Into<u8> for ConnectStatus {
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct NatInfo {
|
||||
public_ips: Vec<u32>,
|
||||
public_port: u16,
|
||||
public_port_range: u16,
|
||||
nat_type: NatType,
|
||||
pub public_ips: Vec<u32>,
|
||||
pub public_port: u16,
|
||||
pub public_port_range: u16,
|
||||
pub nat_type: NatType,
|
||||
}
|
||||
|
||||
impl NatInfo {
|
||||
@@ -118,9 +119,14 @@ impl NatInfo {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn init_nat_test_addr(addrs: Vec<SocketAddr>) {
|
||||
NAT_TEST_ADDRESS.lock().extend_from_slice(&addrs);
|
||||
}
|
||||
|
||||
/// 初始化nat信息
|
||||
pub fn init_nat_info(public_ip: u32, public_port: u16) {
|
||||
match crate::nat::check::public_ip_list() {
|
||||
let addrs = NAT_TEST_ADDRESS.lock().clone();
|
||||
match crate::nat::check::public_ip_list(&addrs) {
|
||||
Ok((nat_type, ips, port_range)) => {
|
||||
let mut public_ips = Vec::new();
|
||||
public_ips.push(public_ip);
|
||||
|
||||
@@ -132,10 +132,10 @@ fn handle(
|
||||
} else {
|
||||
punch.public_port + punch.public_port_range
|
||||
};
|
||||
let k = if max_port - min_port +1 > 60 {
|
||||
let k = if max_port - min_port + 1 > 60 {
|
||||
60
|
||||
} else {
|
||||
max_port - min_port +1
|
||||
max_port - min_port + 1
|
||||
};
|
||||
send_f(min_port as u16, max_port as u16, k as usize)?;
|
||||
}
|
||||
@@ -371,7 +371,7 @@ fn send_punch(udp: &UdpSocket, cur_info: &CurrentDeviceInfo, nat_info: NatInfo)
|
||||
let ip = peer_info.virtual_ip;
|
||||
//只向ip比自己大的发起打洞,避免双方同时发起打洞浪费流量
|
||||
if ip > cur_info.virtual_ip && !DIRECT_ROUTE_TABLE.contains_key(&ip) {
|
||||
log::info!("发起打洞 {:?}, peer_info:{:?}",nat_info,peer_info);
|
||||
log::info!("发起打洞 {:?}, peer_info:{:?}", nat_info, peer_info);
|
||||
let bytes = punch_packet(cur_info.virtual_ip, nat_info.clone(), ip)?;
|
||||
udp.send_to(&bytes, cur_info.connect_server)?;
|
||||
}
|
||||
|
||||
@@ -148,10 +148,10 @@ pub async fn handler_start<F>(
|
||||
) where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::os::unix::io::AsRawFd;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::os::fd::AsRawFd;
|
||||
#[cfg(target_os = "linux")]
|
||||
use std::os::unix::io::AsRawFd;
|
||||
let raw_fd = tun_reader.0.as_raw_fd();
|
||||
tokio::spawn(async move {
|
||||
let _ = status_watch.changed().await;
|
||||
|
||||
+33
-20
@@ -1,7 +1,7 @@
|
||||
use std::io;
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, ToSocketAddrs, UdpSocket};
|
||||
use std::sync::Arc;
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use crossbeam::atomic::AtomicCell;
|
||||
@@ -11,11 +11,11 @@ use tokio::sync::watch;
|
||||
|
||||
use error::*;
|
||||
|
||||
use crate::handle::{
|
||||
ApplicationStatus, ConnectStatus, CurrentDeviceInfo, DEVICE_LIST, DIRECT_ROUTE_TABLE, PeerDeviceInfo,
|
||||
Route, RouteType, SERVER_RT,
|
||||
};
|
||||
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,
|
||||
};
|
||||
|
||||
pub mod error;
|
||||
pub mod handle;
|
||||
@@ -29,6 +29,8 @@ 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,
|
||||
}
|
||||
|
||||
@@ -37,10 +39,12 @@ impl<F> Config<F> {
|
||||
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,
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
if token.is_empty() || token.len() > 64 {
|
||||
return Err(Error::Stop("token invalid".to_string()));
|
||||
@@ -56,6 +60,8 @@ impl<F> Config<F> {
|
||||
token,
|
||||
mac_address,
|
||||
name,
|
||||
server_address,
|
||||
nat_test_server,
|
||||
abnormal_call,
|
||||
})
|
||||
} else {
|
||||
@@ -69,6 +75,8 @@ impl<F> Config<F> {
|
||||
token,
|
||||
mac_address,
|
||||
name,
|
||||
server_address,
|
||||
nat_test_server,
|
||||
abnormal_call,
|
||||
})
|
||||
}
|
||||
@@ -84,8 +92,8 @@ pub struct Switch {
|
||||
|
||||
impl Switch {
|
||||
pub fn start<F>(config: Config<F>) -> Result<Self>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
@@ -109,6 +117,9 @@ impl Switch {
|
||||
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)
|
||||
}
|
||||
@@ -141,11 +152,12 @@ impl Switch {
|
||||
return status == ApplicationStatus::Starting;
|
||||
}
|
||||
pub async fn start_<F>(config: Config<F>) -> Result<Self>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
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 = "nat1.wherewego.top:29875".to_socket_addrs().unwrap().next().unwrap();
|
||||
let server_address = config.server_address;
|
||||
let mut port = 101 as u16;
|
||||
let udp = loop {
|
||||
match UdpSocket::bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from(0), port))) {
|
||||
@@ -215,9 +227,10 @@ impl Switch {
|
||||
drop(wait_group1);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.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) =
|
||||
@@ -249,7 +262,7 @@ impl Switch {
|
||||
drop(wait_group1);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.await;
|
||||
let udp1 = udp.try_clone()?;
|
||||
let wait_group1 = wait_group.clone();
|
||||
let status_sender1 = status_sender.clone();
|
||||
@@ -269,7 +282,7 @@ impl Switch {
|
||||
drop(wait_group1);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.await;
|
||||
}
|
||||
//打洞处理
|
||||
{
|
||||
@@ -291,7 +304,7 @@ impl Switch {
|
||||
drop(wait_group1);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.await;
|
||||
let udp1 = udp.try_clone()?;
|
||||
let wait_group1 = wait_group.clone();
|
||||
let status_sender1 = status_sender.clone();
|
||||
@@ -310,7 +323,7 @@ impl Switch {
|
||||
drop(wait_group1);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.await;
|
||||
let udp1 = udp.try_clone()?;
|
||||
let wait_group1 = wait_group.clone();
|
||||
let status_sender1 = status_sender.clone();
|
||||
@@ -329,7 +342,7 @@ impl Switch {
|
||||
drop(wait_group1);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.await;
|
||||
}
|
||||
//tun数据处理
|
||||
{
|
||||
@@ -350,7 +363,7 @@ impl Switch {
|
||||
drop(wait_group1);
|
||||
},
|
||||
)
|
||||
.await;
|
||||
.await;
|
||||
}
|
||||
Ok(Switch {
|
||||
current_device,
|
||||
|
||||
+27
-9
@@ -21,7 +21,7 @@ use crate::proto::message::NatType;
|
||||
// }
|
||||
|
||||
/// 返回所有公网ip和端口变化范围
|
||||
pub fn public_ip_list() -> io::Result<(NatType, Vec<Ipv4Addr>, u16)> {
|
||||
pub fn public_ip_list(addrs: &Vec<SocketAddr>) -> io::Result<(NatType, Vec<Ipv4Addr>, u16)> {
|
||||
let mut hash_set = HashSet::new();
|
||||
let mut max_port_range = 0;
|
||||
let mut nat_type = NatType::Cone;
|
||||
@@ -41,7 +41,7 @@ pub fn public_ip_list() -> io::Result<(NatType, Vec<Ipv4Addr>, u16)> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let (set, min_port, max_port) = public_ip_list_(&udp)?;
|
||||
let (set, min_port, max_port) = public_ip_list_(&udp, addrs)?;
|
||||
drop(udp);
|
||||
let port_range = max_port - min_port;
|
||||
//有多个ip或者端口有变化,说明是对称nat
|
||||
@@ -69,19 +69,24 @@ pub fn public_ip_list() -> io::Result<(NatType, Vec<Ipv4Addr>, u16)> {
|
||||
/// - 电信4g:对称网络只有一个ip 公网端口比较连续
|
||||
/// - 综上:客户端使用小端口,针对对称网络 尝试所有ip 公网端口+-变化量的范围
|
||||
/// - 打通概率 移动宽带=电信宽带>联调宽带>电信4g>移动4g>>联调4g
|
||||
pub fn public_ip_list_(udp: &UdpSocket) -> io::Result<(HashSet<Ipv4Addr>, u16, u16)> {
|
||||
pub fn public_ip_list_(
|
||||
udp: &UdpSocket,
|
||||
addrs: &Vec<SocketAddr>,
|
||||
) -> io::Result<(HashSet<Ipv4Addr>, u16, u16)> {
|
||||
// println!("local port {:?}", udp.local_addr().unwrap().port());
|
||||
udp.set_read_timeout(Some(Duration::from_millis(300)))?;
|
||||
let mut buf = [0u8; 128];
|
||||
let _ = udp.send_to(b"NatTest", "nat1.wherewego.top:35061")?;
|
||||
let _ = udp.send_to(b"NatTest", "nat1.wherewego.top:35062")?;
|
||||
let _ = udp.send_to(b"NatTest", "nat2.wherewego.top:35061")?;
|
||||
let _ = udp.send_to(b"NatTest", "nat2.wherewego.top:35062")?;
|
||||
for addr in addrs {
|
||||
let _ = udp.send_to(b"NatTest", addr)?;
|
||||
}
|
||||
// let _ = udp.send_to(b"NatTest", "nat1.wherewego.top:35062")?;
|
||||
// let _ = udp.send_to(b"NatTest", "nat2.wherewego.top:35061")?;
|
||||
// let _ = udp.send_to(b"NatTest", "nat2.wherewego.top:35062")?;
|
||||
let mut hash_set = HashSet::new();
|
||||
let mut count = 0;
|
||||
let mut min_port = 65535;
|
||||
let mut max_port = 0;
|
||||
for _ in 0..4 {
|
||||
for _ in 0..addrs.len() {
|
||||
if let Ok(len) = udp.recv(&mut buf) {
|
||||
if len != 16 || &buf[..10] != &b"NatType213"[..] {
|
||||
continue;
|
||||
@@ -152,6 +157,19 @@ pub fn nat_test_() -> io::Result<NatType> {
|
||||
#[test]
|
||||
fn nat_test_run() {
|
||||
let udp = UdpSocket::bind("0.0.0.0:101").unwrap();
|
||||
let print = public_ip_list_(&udp).unwrap();
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs, UdpSocket};
|
||||
let addrs = vec![
|
||||
"nat1.wherewego.top:35062"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap(),
|
||||
"nat2.wherewego.top:35062"
|
||||
.to_socket_addrs()
|
||||
.unwrap()
|
||||
.next()
|
||||
.unwrap(),
|
||||
];
|
||||
let print = public_ip_list_(&udp, &addrs).unwrap();
|
||||
println!("{:?}", print);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use crate::tun_device::{TunReader, TunWriter};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub fn create_tun(
|
||||
address: Ipv4Addr,
|
||||
|
||||
Reference in New Issue
Block a user