Compare commits

...
31 Commits
Author SHA1 Message Date
lubeilin 94d6caef7e 修复连接tcp地址的问题 2023-12-26 22:27:16 +08:00
lubeilin 364012f9dd fmt 2023-12-26 21:47:01 +08:00
lubeilin cf4b1f418f 忽略地址校验 2023-12-26 21:46:41 +08:00
lubeilin c6465977ef 将ipv4转换成ipv6 2023-12-26 21:46:23 +08:00
lubeilin c577e6381f 将ipv4转换成ipv6 2023-12-25 23:06:47 +08:00
lubeilin 134e31f563 fmt 2023-12-24 13:42:41 +08:00
lubeilin 0580b89f48 升级版本号 2023-12-24 12:22:34 +08:00
lubeilin 37080af275 支持ipv6服务端 2023-12-24 12:00:44 +08:00
lubeilin 26d68ac059 版本改为1.2.7 2023-10-31 20:49:25 +08:00
lubeilin 6292c1c381 去除溢出检查 2023-10-31 20:49:16 +08:00
lubeilin b0c3f25a29 使用读写锁简化操作,增加延迟优先选项 2023-10-31 20:48:38 +08:00
lubeilin d2e09d3da5 增加配置文件的参数说明 2023-10-11 20:46:39 +08:00
lbl8603 293c5b90a4 Merge pull request #22 from taotieren/contrib
Update README.md
2023-10-11 09:19:37 +08:00
taotieren e2323361f9 Update README.md 2023-10-10 23:23:25 +08:00
lbl8603 d05cff99ee Merge pull request #21 from taotieren/aur
Update README.md
2023-10-10 22:52:30 +08:00
taotieren e9b1b2ef3b Update README.md 2023-10-10 22:31:38 +08:00
lbl8603 a8ea2c14fc Merge pull request #20 from taotieren/aur
Add AUR vnt-git
2023-10-10 22:22:10 +08:00
taotieren 0688cb4515 Add AUR vnt-git 2023-10-10 22:18:37 +08:00
lubeilin c3261d7a57 修改版本为1.2.6 2023-10-09 21:20:10 +08:00
lubeilin ef8d13f61b 编译features增加ring 2023-10-09 20:56:58 +08:00
lubeilin fc104d5dee 增加参数关闭ip代理 2023-10-09 20:56:04 +08:00
lubeilin 9ad0525216 减少复制 2023-10-08 20:52:12 +08:00
lubeilin 3ea1250b53 完善编译和参数说明 2023-10-08 20:03:14 +08:00
lubeilin 9df34207f7 解决不同features编译时告警的问题 2023-10-08 17:46:31 +08:00
lubeilin dacce892ff 可选ip代理,关闭后可使用外部命令来进行ip转发 2023-10-08 17:16:02 +08:00
lubeilin a9495f1d30 升级tap相关依赖 2023-10-06 22:44:02 +08:00
lubeilin 0892c6eee9 修复进程异常退出的问题 2023-10-06 22:25:30 +08:00
lubeilin f746eadcf1 fmt 2023-10-06 22:22:35 +08:00
lubeilin da2371541c 修改依赖版本 2023-10-06 22:22:22 +08:00
lubeilin cca91d4331 tcp改为使用同步方法 2023-10-06 22:21:29 +08:00
lubeilin 11aa3b1d2c 修改features说明 2023-09-28 10:35:50 +08:00
36 changed files with 996 additions and 822 deletions
+3 -3
View File
@@ -47,13 +47,13 @@ jobs:
FEATURES: ring-cipher,openssl-vendored
- TARGET: aarch64-unknown-linux-musl # tested on aws t4g.nano in alpine container
OS: ubuntu-latest
FEATURES: default
FEATURES: ring-cipher,openssl-vendored
- TARGET: armv7-unknown-linux-musleabihf # raspberry pi 2-3-4, not tested
OS: ubuntu-latest
FEATURES: openssl-vendored
- TARGET: arm-unknown-linux-musleabihf # raspberry pi 0-1, not tested
OS: ubuntu-latest
FEATURES: openssl-vendored
FEATURES: ring-cipher,openssl-vendored
- TARGET: x86_64-apple-darwin # tested on a mac, is not properly signed so there are security warnings
OS: macos-latest
FEATURES: ring-cipher,openssl-vendored
@@ -68,7 +68,7 @@ jobs:
FEATURES: ring-cipher,openssl-vendored
- TARGET: mipsel-unknown-linux-musl # openwrt
OS: ubuntu-latest
FEATURES: openssl-vendored
FEATURES: openssl-vendored,ring-cipher
- TARGET: mips-unknown-linux-musl # openwrt
OS: ubuntu-latest
FEATURES: openssl-vendored
-1
View File
@@ -6,7 +6,6 @@ opt-level = 'z'
debug = 0
debug-assertions = false
strip= "debuginfo"
overflow-checks = true
lto = true
panic = 'abort'
incremental = false
+79 -2
View File
@@ -81,13 +81,84 @@ features说明
| aes_cbc | 支持aes_cbc加密 | 是 |
| aes_ecb | 支持aes_ecb加密 | 是 |
| aes_gcm | 支持aes_gcm加密 | 是 |
| aes_ecb | 支持aes_ecb加密 | 是 |
| sm4_cbc | 支持sm4_cbc加密 | 是 |
| server_encrypt | 支持服务端加密 | 是 |
| ip_proxy | 内置ip代理 | 是 |
如果编译时去除了内置的ip代理(或使用--no-proxy关闭了代理),则可以使用网卡NAT转发来实现点对网,
一般来说使用网卡NAT转发会比内置的ip代理性能更好
<details> <summary>NAT配置可参考如下示例,点击展开</summary>
### 在出口一端做如下配置
注意原有的-i(入口)和-o(出口)的参数不能少
### windows
参考 https://learn.microsoft.com/zh-cn/virtualization/hyper-v-on-windows/user-guide/setup-nat-network
```shell
#设置nat,名字可以自己取,网段是vnt的网段
New-NetNat -Name vntnat -InternalIPInterfaceAddressPrefix 10.26.0.0/24
#查看设置
Get-NetNat
```
### linux
```shell
# 开启ip转发
sudo sysctl -w net.ipv4.ip_forward=1
# 开启nat转发 表示来源10.26.0.0/24的数据通过nat映射后再从vnt-tun以外的其他网卡发出去
sudo iptables -t nat -A POSTROUTING ! -o vnt-tun -s 10.26.0.0/24 -j MASQUERADE
# 或者这样 表示来源10.26.0.0/24的数据通过nat映射后再从eth0网卡发出去
sudo iptables -t nat -A POSTROUTING -o eth0 -s 10.26.0.0/24 -j MASQUERADE
# 查看设置
iptables -vnL -t nat
```
### Arch Linux
[![Packaging status](https://repology.org/badge/vertical-allrepos/vnt.svg)](https://repology.org/project/vnt/versions)
- 通过 AUR 安装 [vnt-git](https://aur.archlinux.org/packages/vnt-git)
```bash
yay -Syu vnt
```
- 通过 `systemd` 设置开机自启及配置
```bash
sudo systemctl enable --now vnt-cli@
sudo systemctl status vnt-cli@
```
- 启用内置 `IPv4` 转发规则
```bash
sudo sysctl --system
```
- 通过内置防火墙文件配置防火墙转发规则
```bash
sudo cat /etc/vnt/iptables-vnt.rules >> /etc/iptables/iptables.rules
sudo iptables-restore iptables.rules
```
### macos
```shell
# 开启ip转发
sudo sysctl -w net.ipv4.ip_forward=1
# 配置NAT转发规则
# 在/etc/pf.conf文件中添加以下规则,en0是出口网卡,10.26.0.0/24是来源网段
nat on en0 from 10.26.0.0/24 to any -> (en0)
# 加载规则
sudo pfctl -f /etc/pf.conf -e
```
</details>
### 支持平台
- Mac
- Linux
- Arch Linux `yay -Syu vnt`
- Windows
- 默认使用tun网卡 依赖wintun.dll([win-tun](https://www.wintun.net/))(将dll放到同目录下,建议使用版本0.14.1)
- 使用tap网卡 依赖tap-windows([win-tap](https://build.openvpn.net/downloads/releases/))(建议使用版本9.24.7)
@@ -187,10 +258,16 @@ vnt默认使用10.26.0.0/24网段,和本地网络适配器的ip冲突
### 交流群
QQ:1034868233
QQ: 1034868233
### 其他
可使用社区小伙伴搭建的中继服务器
1. -s vnt.8443.eu.org:29871
### 参与贡献
<a href="https://github.com/lbl8603/vnt/graphs/contributors">
<img src="https://contrib.rocks/image?repo=lbl8603/vnt" />
</a>
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "common"
version = "1.2.5"
version = "1.2.8"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+4 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "vnt-cli"
version = "1.2.5"
version = "1.2.8"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -15,7 +15,7 @@ os_info = "3.7.0"
dirs = "5.0.1"
serde = "1.0"
serde_json = "1.0.94"
serde_yaml = "0.9.25"
serde_yaml = "0.8.26"
log = "0.4.17"
log4rs = "1.2.0"
[dependencies.uuid]
@@ -31,7 +31,7 @@ sudo = "0.6.0"
winapi = { version = "0.3.9", features = ["handleapi", "processthreadsapi", "winnt", "securitybaseapi", "impl-default"] }
[features]
default = ["server_encrypt","aes_gcm","aes_cbc","aes_ecb","sm4_cbc"]
default = ["server_encrypt","aes_gcm","aes_cbc","aes_ecb","sm4_cbc","ip_proxy"]
openssl = ["vnt/openssl"]
openssl-vendored = ["vnt/openssl-vendored"]
ring-cipher = ["vnt/ring-cipher"]
@@ -40,6 +40,6 @@ aes_ecb=["vnt/aes_ecb"]
sm4_cbc=["vnt/sm4_cbc"]
aes_gcm=["vnt/aes_gcm"]
server_encrypt=["vnt/server_encrypt"]
ip_proxy=["vnt/ip_proxy"]
[build-dependencies]
embed-manifest = "1.4.0"
+10 -1
View File
@@ -80,6 +80,13 @@
取值ipv4/ipv6,选择只使用ipv4打洞或者只使用ipv6打洞,默认两则都会使用
### --port `<port>`
取值0~65535,指定本地监听的端口,默认取随机端口
### --cmd
开启交互式命令,开启后可以直接在窗口下输入命令,如需后台运行请勿开启
### --first_latency
优先使用低延迟通道,默认情况下优先使用p2p通道,某些情况下可能p2p比客户端中继延迟更高,可使用此参数进行优化传输
### --no-proxy
关闭内置的ip代理,内置的代理较为简单,而且一般来说直接使用网卡NAT转发性能会更高,
有需要可以自行配置NAT转发,[可参考‘编译’小节中的NAT配置](https://github.com/lbl8603/vnt#%E7%BC%96%E8%AF%91)
### -f `<conf>`
指定配置文件
配置文件采用yaml格式,可参考:
@@ -107,9 +114,11 @@ server_encrypt: true #服务端加密
parallel: 1 #任务并行度
cipher_model: aes_gcm #客户端加密算法
finger: false #关闭数据指纹
punch_model: ipv4 #打洞模式
punch_model: ipv4 #打洞模式
port: 0 #使用随机端口
cmd: false #关闭控制台输入
no_proxy: false #是否关闭内置代理,true为关闭
first_latency: false #是否优先低延迟通道,默认为false,表示优先使用p2p通道
```
或者需要哪个配置就加哪个,当然token是必须的
+7
View File
@@ -25,6 +25,7 @@ pub struct FileConfig {
pub tcp: bool,
pub ip: Option<String>,
pub relay: bool,
pub no_proxy: bool,
pub server_encrypt: bool,
pub parallel: usize,
pub cipher_model: String,
@@ -32,6 +33,7 @@ pub struct FileConfig {
pub punch_model: String,
pub port: u16,
pub cmd: bool,
pub first_latency: bool,
}
impl Default for FileConfig {
@@ -55,6 +57,7 @@ impl Default for FileConfig {
tcp: false,
ip: None,
relay: false,
no_proxy: false,
server_encrypt: false,
parallel: 1,
cipher_model: "aes_gcm".to_string(),
@@ -62,6 +65,7 @@ impl Default for FileConfig {
punch_model: "".to_string(),
port: 0,
cmd: false,
first_latency: false,
}
}
}
@@ -145,12 +149,15 @@ pub fn read_config(file_path: &str) -> io::Result<(Config, bool)> {
file_conf.tcp,
virtual_ip,
file_conf.relay,
#[cfg(feature = "ip_proxy")]
file_conf.no_proxy,
file_conf.server_encrypt,
file_conf.parallel,
cipher_model,
file_conf.finger,
punch_model,
file_conf.port,
file_conf.first_latency,
);
Ok((config, file_conf.cmd))
}
+36 -6
View File
@@ -58,6 +58,8 @@ fn main() {
opts.optopt("", "punch", "取值ipv4/ipv6", "<punch>");
opts.optopt("", "port", "监听的端口", "<port>");
opts.optflag("", "cmd", "开启窗口输入");
opts.optflag("", "no-proxy", "关闭内置代理");
opts.optflag("", "first-latency", "优先延迟");
opts.optopt("f", "", "配置文件", "<conf>");
//"后台运行时,查看其他设备列表"
opts.optflag("", "list", "后台运行时,查看其他设备列表");
@@ -258,6 +260,9 @@ fn main() {
.unwrap_or(PunchModel::All);
let port = matches.opt_get::<u16>("port").unwrap_or(None).unwrap_or(0);
let cmd = matches.opt_present("cmd");
#[cfg(feature = "ip_proxy")]
let no_proxy = matches.opt_present("no-proxy");
let first_latency = matches.opt_present("first-latency");
let config = Config::new(
tap,
token,
@@ -274,12 +279,15 @@ fn main() {
tcp_channel,
virtual_ip,
relay,
#[cfg(feature = "ip_proxy")]
no_proxy,
server_encrypt,
parallel,
cipher_model,
finger,
punch_model,
port,
first_latency,
);
(config, cmd)
};
@@ -292,23 +300,23 @@ fn main() {
#[tokio::main]
async fn main0(config: Config, show_cmd: bool) {
let server_encrypt = config.server_encrypt;
let mut vnt_util = VntUtil::new(config).await.unwrap();
let mut vnt_util = VntUtil::new(config).unwrap();
let mut conn_count = 0;
let response = loop {
if conn_count > 0 {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}
conn_count += 1;
if let Err(e) = vnt_util.connect().await {
if let Err(e) = vnt_util.connect() {
println!("connect server failed {}", e);
return;
}
match vnt_util.handshake().await {
match vnt_util.handshake() {
Ok(response) => {
if server_encrypt {
let finger = response.unwrap().finger().unwrap();
println!("{}{}", green("server fingerprint:".to_string()), finger);
match vnt_util.secret_handshake().await {
match vnt_util.secret_handshake() {
Ok(_) => {}
Err(e) => {
match e {
@@ -328,7 +336,7 @@ async fn main0(config: Config, show_cmd: bool) {
}
}
}
match vnt_util.register().await {
match vnt_util.register() {
Ok(response) => {
break response;
}
@@ -483,6 +491,23 @@ fn print_usage(program: &str, _opts: Options) {
println!(" -i <in-ip> 配置点对网(IP代理)时使用,-i 192.168.0.0/24,10.26.0.3表示允许接收网段192.168.0.0/24的数据");
println!(" 并转发到10.26.0.3,可指定多个网段");
println!(" -o <out-ip> 配置点对网时使用,-o 192.168.0.0/24表示允许将数据转发到192.168.0.0/24,可指定多个网段");
#[cfg(not(feature = "ip_proxy"))]
println!(" 注意需要在系统配置ip转发才可正常使用");
#[cfg(not(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
)))]
let enums = String::new();
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
let mut enums = String::new();
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
enums.push_str("/aes_gcm");
@@ -511,10 +536,15 @@ fn print_usage(program: &str, _opts: Options) {
&enums[1..]
);
}
println!(" --finger 增加数据指纹校验,可增加安全性,如果服务端开启指纹校验,则客户端也必须开启");
if !enums.is_empty() {
println!(" --finger 增加数据指纹校验,可增加安全性,如果服务端开启指纹校验,则客户端也必须开启");
}
println!(" --punch <punch> 取值ipv4/ipv6ipv4表示仅使用ipv4打洞");
println!(" --port <port> 取值0~65535,指定本地监听的端口,默认取随机端口");
println!(" --cmd 开启交互式命令,使用此参数开启控制台输入");
#[cfg(feature = "ip_proxy")]
println!(" --no-proxy 关闭内置代理,如需点对网则需要配置网卡NAT转发");
println!(" --first-latency 优先低延迟的通道,默认情况优先使用p2p通道");
println!();
println!(
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "vnt-jni"
version = "1.2.5"
version = "1.2.8"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+3
View File
@@ -66,6 +66,7 @@ fn new_sync(env: &mut JNIEnv, config: JObject) -> Result<VntUtilSync, Error> {
let cipher_model = to_string_not_null(env, &config, "cipherModel")?;
let tcp = env.get_field(&config, "tcp", "Z")?.z()?;
let finger = env.get_field(&config, "finger", "Z")?.z()?;
let first_latency = env.get_field(&config, "firstLatency", "Z")?.z()?;
let in_ips = to_string(env, &config, "inIps")?;
let out_ips = to_string(env, &config, "outIps")?;
let port = env.get_field(&config, "port", "I")?.i()? as u16;
@@ -146,11 +147,13 @@ fn new_sync(env: &mut JNIEnv, config: JObject) -> Result<VntUtilSync, Error> {
None,
false,
false,
false,
1,
cipher_model,
finger,
PunchModel::All,
port,
first_latency,
);
match VntUtilSync::new(config) {
Ok(vnt_util) => Ok(vnt_util),
+10 -10
View File
@@ -1,18 +1,18 @@
[package]
name = "vnt"
version = "1.2.5"
version = "1.2.8"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
packet = { path = "./packet" }
bytes = "1.3.0"
bytes = "1.5.0"
log = "0.4.17"
libc = "0.2.137"
crossbeam-utils = "0.8"
crossbeam-epoch = "0.9.15"
dashmap = "5.5.1"
dashmap = {version = "5.5.3",optional = true}
parking_lot = "0.12.1"
rand = "0.8.5"
sha2 = { version = "0.10.6", features = ["oid"] }
@@ -21,13 +21,13 @@ protobuf = "3.2.0"
socket2 = { version = "0.5.2", features = ["all"] }
tokio = { version = "1.32.0", features = ["full"] }
aes-gcm = { version = "0.10.2",optional = true }
ring = { version = "0.16.20", optional = true }
ring = { version = "0.17.0", optional = true }
cbc = {version = "0.1.2",optional = true}
ecb = {version = "0.1.2",optional = true}
aes = "0.8.3"
stun-format = { version = "1.0.1", features = ["fmt", "rfc3489"] }
rsa = { version = "0.7.2", features = [] ,optional = true}
spki = { version = "0.6.0", features = ["fingerprint", "alloc"] ,optional = true}
rsa = { version = "0.9.2", features = [] ,optional = true}
spki = { version = "0.7.2", features = ["fingerprint", "alloc","base64"] ,optional = true}
openssl-sys = { git = "https://github.com/lbl8603/rust-openssl" ,optional = true}
libsm = {git="https://github.com/lbl8603/libsm" ,optional = true}
@@ -36,7 +36,7 @@ tun = { path = "./rust-tun" }
[target.'cfg(target_os = "windows")'.dependencies]
win-tun-tap = { path = "./win-tun-tap" }
libloading = "0.7.4"
libloading = "0.8.0"
[build-dependencies]
@@ -44,7 +44,7 @@ protobuf-codegen = "3.2.0"
protoc-bin-vendored = "3.0.0"
[features]
default = ["server_encrypt","aes_gcm","aes_cbc","aes_ecb","sm4_cbc"]
default = ["server_encrypt","aes_gcm","aes_cbc","aes_ecb","sm4_cbc","ip_proxy"]
openssl = ["openssl-sys"]
# 从源码编译
openssl-vendored = ["openssl-sys/vendored"]
@@ -53,5 +53,5 @@ aes_cbc=["cbc"]
aes_ecb=["ecb"]
sm4_cbc=["libsm"]
aes_gcm=["aes-gcm"]
server_encrypt =["rsa","spki"]
server_encrypt =["aes-gcm","rsa","spki"]
ip_proxy=["dashmap"]
+8 -1
View File
@@ -76,7 +76,14 @@ impl<B: AsRef<[u8]>> TcpPacket<B> {
Ok(packet)
}
}
impl<B: AsRef<[u8]> + AsMut<[u8]>> TcpPacket<B> {
pub fn set_source_ip(&mut self, value: Ipv4Addr) {
self.source_ip = value;
}
pub fn set_destination_ip(&mut self, value: Ipv4Addr) {
self.destination_ip = value;
}
}
impl<B: AsRef<[u8]> + AsMut<[u8]>> TcpPacket<B> {
fn set_checksum(&mut self, value: u16) {
self.buffer.as_mut()[16..18].copy_from_slice(&value.to_be_bytes())
+183 -354
View File
@@ -1,40 +1,35 @@
use std::collections::HashMap;
use std::io;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr};
use std::ops::Sub;
use std::sync::atomic::Ordering;
use std::io::{Read, Write};
use std::net::UdpSocket as StdUdpSocket;
use std::net::{Ipv4Addr, Shutdown, SocketAddr};
use std::net::{SocketAddrV6, TcpStream};
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::{io, thread};
use crossbeam_epoch::{Atomic, Owned};
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use std::net::UdpSocket as StdUdpSocket;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::tcp::OwnedReadHalf;
use tokio::net::{TcpStream, UdpSocket};
use parking_lot::RwLock;
use tokio::net::UdpSocket;
use tokio::sync::watch::{channel, Receiver, Sender};
use crate::channel::punch::NatType;
use crate::channel::{Route, RouteKey, Status, TCP_ID, UDP_ID, UDP_V6_ID};
use crate::channel::{Route, RouteKey, Status, TCP_ID, UDP_ID};
use crate::core::status::VntWorker;
use crate::handle::recv_handler::ChannelDataHandler;
use crate::handle::CurrentDeviceInfo;
use crate::ip_proxy::DashMapNew;
pub struct ContextInner {
//udp用于打洞、服务端通信(可选)
pub(crate) main_channel: Arc<StdUdpSocket>,
pub(crate) main_channel_ipv6: Option<Arc<StdUdpSocket>>,
//在udp的基础上,可以选择使用tcp和服务端通信
pub(crate) main_tcp_channel: Option<tokio::sync::mpsc::Sender<Vec<u8>>>,
pub(crate) route_table: Atomic<HashMap<Ipv4Addr, Vec<Route>>>,
pub(crate) route_table_time: DashMap<(RouteKey, Ipv4Addr), Instant>,
pub(crate) main_tcp_channel: Option<std::sync::mpsc::SyncSender<Vec<u8>>>,
pub(crate) route_table: RwLock<HashMap<Ipv4Addr, Vec<(Route, AtomicCell<Instant>)>>>,
pub(crate) status_receiver: Receiver<Status>,
pub(crate) status_sender: Sender<Status>,
pub(crate) udp_map: Atomic<HashMap<usize, Arc<UdpSocket>>>,
pub(crate) udp_map: RwLock<HashMap<usize, Arc<UdpSocket>>>,
pub(crate) channel_num: usize,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
first_latency: bool,
}
#[derive(Clone)]
@@ -45,25 +40,24 @@ pub struct Context {
impl Context {
pub fn new(
main_channel: Arc<StdUdpSocket>,
main_channel_ipv6: Option<Arc<StdUdpSocket>>,
main_tcp_channel: Option<tokio::sync::mpsc::Sender<Vec<u8>>>,
main_tcp_channel: Option<std::sync::mpsc::SyncSender<Vec<u8>>>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
_channel_num: usize,
first_latency: bool,
) -> Self {
//当前版本只支持一个通道
let channel_num = 1;
let (status_sender, status_receiver) = channel(Status::Cone);
let inner = Arc::new(ContextInner {
main_channel,
main_channel_ipv6,
main_tcp_channel,
route_table: Atomic::new(HashMap::with_capacity(16)),
route_table_time: DashMap::new_cap(16),
route_table: RwLock::new(HashMap::with_capacity(16)),
status_receiver,
status_sender,
udp_map: Atomic::new(HashMap::with_capacity(16)),
udp_map: RwLock::new(HashMap::with_capacity(16)),
channel_num,
current_device,
first_latency,
});
Self { inner }
}
@@ -78,17 +72,14 @@ impl Context {
}
pub fn close(&self) -> io::Result<()> {
let _ = self.inner.status_sender.send(Status::Close);
if let Ok(port) = self.main_local_ipv4_port() {
if let Ok(port) = self.main_local_udp_port() {
let _ = StdUdpSocket::bind("127.0.0.1:0")?.send_to(
b"stop",
SocketAddr::V4(std::net::SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)),
);
}
if let Ok(port) = self.main_local_ipv6_port() {
let _ = StdUdpSocket::bind("[::]:0")?.send_to(
b"stop",
SocketAddr::V6(std::net::SocketAddrV6::new(Ipv6Addr::LOCALHOST, port, 0, 0)),
);
if let Some(tcp) = &self.inner.main_tcp_channel {
let _ = tcp.send(vec![]);
}
Ok(())
}
@@ -111,63 +102,26 @@ impl Context {
pub fn switch_to_symmetric(&self) {
let _ = self.inner.status_sender.send(Status::Symmetric);
}
pub fn main_local_ipv4_port(&self) -> io::Result<u16> {
pub fn main_local_udp_port(&self) -> io::Result<u16> {
self.inner.main_channel.local_addr().map(|k| k.port())
}
pub fn main_local_ipv6_port(&self) -> io::Result<u16> {
if let Some(ipv6) = &self.inner.main_channel_ipv6 {
ipv6.local_addr().map(|k| k.port())
} else {
Err(io::Error::new(io::ErrorKind::Other, "not ipv6"))
}
}
fn insert_udp(&self, id: usize, udp: Arc<UdpSocket>) {
self.insert_udp_(id, Some(udp))
self.inner.udp_map.write().insert(id, udp);
}
fn remove_udp(&self, id: usize) {
self.insert_udp_(id, None)
self.inner.udp_map.write().remove(&id);
}
fn insert_udp_(&self, id: usize, udp: Option<Arc<UdpSocket>>) {
let guard = &crossbeam_epoch::pin();
let udp_map = &self.inner.udp_map;
let mut udp_map_shared = self.inner.udp_map.load(Ordering::Relaxed, guard);
loop {
let mut map = unsafe { udp_map_shared.as_ref().unwrap().clone() };
match udp.clone() {
None => {
map.remove(&id);
}
Some(udp) => {
map.insert(id, udp);
}
}
match udp_map.compare_exchange(
udp_map_shared,
Owned::new(map),
Ordering::Relaxed,
Ordering::Relaxed,
guard,
) {
Ok(p) => unsafe {
guard.defer_destroy(p);
return;
},
Err(e) => {
udp_map_shared = e.current;
}
}
}
}
pub fn send_main_udp(&self, buf: &[u8], addr: SocketAddr) -> io::Result<usize> {
if addr.is_ipv6() {
if let Some(udp_ipv6) = &self.inner.main_channel_ipv6 {
udp_ipv6.send_to(buf, addr)
} else {
Err(io::Error::new(io::ErrorKind::Other, "not ipv6"))
}
} else {
self.inner.main_channel.send_to(buf, addr)
#[inline]
pub fn send_main_udp(&self, buf: &[u8], mut addr: SocketAddr) -> io::Result<usize> {
if let SocketAddr::V4(ipv4) = addr {
addr = SocketAddr::V6(SocketAddrV6::new(
ipv4.ip().to_ipv6_mapped(),
ipv4.port(),
0,
0,
));
}
self.inner.main_channel.send_to(buf, addr)
}
pub fn send_main(&self, buf: &[u8], addr: SocketAddr) -> io::Result<usize> {
@@ -183,20 +137,12 @@ impl Context {
}
pub(crate) fn try_send_all(&self, buf: &[u8], addr: SocketAddr) -> io::Result<()> {
let table = unsafe {
let guard = &crossbeam_epoch::pin();
self.inner
.udp_map
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
.clone()
};
let table = self.inner.udp_map.read();
if table.is_empty() {
log::error!("udp列表为空,addr={}", addr);
return Ok(());
}
for (_, udp) in table {
for (_, udp) in table.iter() {
//使用ipv6的udp发送ipv4报文会出错
if let Err(e) = udp.try_send_to(buf, addr) {
log::error!("{:?}", e);
@@ -214,32 +160,22 @@ impl Context {
self.try_send_by_key(buf, &route.route_key())
}
fn get_route_by_id(&self, id: &Ipv4Addr) -> io::Result<Route> {
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
if let Some(v) = table.get(id) {
if let Some(v) = self.inner.route_table.read().get(id) {
if v.is_empty() {
return Err(io::Error::new(io::ErrorKind::NotFound, "route not found"));
}
let route = v[0];
let (route, time) = &v[0];
if route.rt == 199 {
//这通常是刚加入路由,直接放弃使用,避免抖动
return Err(io::Error::new(io::ErrorKind::NotFound, "route not found"));
}
if !route.is_p2p() {
if let Some(time) = self.inner.route_table_time.get(&(route.route_key(), *id)) {
//借道传输时,长时间不通信的通道不使用
if time.value().elapsed() > Duration::from_secs(6) {
return Err(io::Error::new(io::ErrorKind::NotFound, "route time out"));
}
//借道传输时,长时间不通信的通道不使用
if time.load().elapsed() > Duration::from_secs(6) {
return Err(io::Error::new(io::ErrorKind::NotFound, "route time out"));
}
}
return Ok(route);
return Ok(*route);
}
Err(io::Error::new(io::ErrorKind::NotFound, "route not found"))
}
@@ -248,7 +184,7 @@ impl Context {
match route_key.index {
TCP_ID => {
if let Some(sender) = &self.inner.main_tcp_channel {
if sender.send(buf.to_vec()).await.is_ok() {
if sender.send(buf.to_vec()).is_ok() {
Ok(buf.len())
} else {
Err(io::Error::new(io::ErrorKind::Other, "send_by_key err"))
@@ -257,14 +193,7 @@ impl Context {
Err(io::Error::new(io::ErrorKind::Other, "send_by_key err"))
}
}
UDP_ID => self.inner.main_channel.send_to(buf, route_key.addr),
UDP_V6_ID => {
if let Some(udp_ipv6) = &self.inner.main_channel_ipv6 {
udp_ipv6.send_to(buf, route_key.addr)
} else {
Err(io::Error::new(io::ErrorKind::Other, "not ipv6 udp"))
}
}
UDP_ID => self.send_main_udp(buf, route_key.addr),
_ => {
if let Some(udp) = self.get_udp_by_route(route_key) {
return udp.send_to(buf, route_key.addr).await;
@@ -286,14 +215,7 @@ impl Context {
Err(io::Error::new(io::ErrorKind::Other, "send_by_key err"))
}
}
UDP_ID => self.inner.main_channel.send_to(buf, route_key.addr),
UDP_V6_ID => {
if let Some(udp_ipv6) = &self.inner.main_channel_ipv6 {
udp_ipv6.send_to(buf, route_key.addr)
} else {
Err(io::Error::new(io::ErrorKind::Other, "not ipv6 udp"))
}
}
UDP_ID => self.send_main_udp(buf, route_key.addr),
_ => {
if let Some(udp) = self.get_udp_by_route(route_key) {
return udp.try_send_to(buf, route_key.addr);
@@ -303,15 +225,7 @@ impl Context {
}
}
fn get_udp_by_route(&self, route_key: &RouteKey) -> Option<Arc<UdpSocket>> {
let guard = &crossbeam_epoch::pin();
let udp_map = unsafe {
self.inner
.udp_map
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
udp_map.get(&route_key.index).cloned()
self.inner.udp_map.read().get(&route_key.index).cloned()
}
pub fn add_route_if_absent(&self, id: Ipv4Addr, route: Route) {
@@ -322,105 +236,60 @@ impl Context {
}
fn add_route_(&self, id: Ipv4Addr, route: Route, only_if_absent: bool) {
let key = route.route_key();
let guard = &crossbeam_epoch::pin();
let route_table = &self.inner.route_table;
let mut table_share = route_table.load(Ordering::Relaxed, guard);
loop {
let mut table = unsafe { table_share.as_ref().unwrap().clone() };
let list = table.entry(id).or_insert_with(|| Vec::with_capacity(4));
let mut exist = false;
for x in list.iter_mut() {
if x.metric < route.metric {
//不能比当前的路径更长
let mut route_table = self.inner.route_table.write();
let list = route_table
.entry(id)
.or_insert_with(|| Vec::with_capacity(4));
let mut exist = false;
for (x, time) in list.iter_mut() {
if x.metric < route.metric {
//不能比当前的路径更长
return;
}
if x.route_key() == key {
if only_if_absent {
return;
}
if x.route_key() == key {
if only_if_absent {
return;
}
x.metric = route.metric;
x.rt = route.rt;
exist = true;
break;
}
}
if exist {
list.sort_by_key(|k| k.sort_key());
} else {
if route.metric == 1 {
//添加了直连的则排除非直连的
list.retain(|k| k.metric == 1);
}
list.push(route);
list.sort_by_key(|k| k.sort_key());
let max_len = self.inner.channel_num + 1;
if list.len() > max_len {
list.truncate(max_len);
}
}
match route_table.compare_exchange(
table_share,
Owned::new(table),
Ordering::Relaxed,
Ordering::Relaxed,
guard,
) {
Ok(p) => unsafe {
guard.defer_destroy(p);
break;
},
Err(e) => {
table_share = e.current;
}
x.metric = route.metric;
x.rt = route.rt;
exist = true;
time.store(Instant::now());
break;
}
}
self.inner
.route_table_time
.insert((key, id), Instant::now().sub(Duration::from_secs(10)));
if exist {
list.sort_by_key(|(k, _)| k.rt);
} else {
if route.metric == 1 && !self.inner.first_latency {
//非优先延迟的情况下 添加了直连的则排除非直连的
list.retain(|(k, _)| k.metric == 1);
}
list.sort_by_key(|(k, _)| k.rt);
let max_len = self.inner.channel_num;
if list.len() > max_len {
list.truncate(max_len);
}
list.push((route, AtomicCell::new(Instant::now())));
}
}
pub fn route(&self, id: &Ipv4Addr) -> Option<Vec<Route>> {
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
if let Some(v) = table.get(id) {
Some(v.clone())
if let Some(v) = self.inner.route_table.read().get(id) {
Some(v.iter().map(|(i, _)| *i).collect())
} else {
None
}
}
pub fn route_one(&self, id: &Ipv4Addr) -> Option<Route> {
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
if let Some(v) = table.get(id) {
v.first().map(|v| *v)
if let Some(v) = self.inner.route_table.read().get(id) {
v.first().map(|(i, _)| *i)
} else {
None
}
}
pub fn route_to_id(&self, route_key: &RouteKey) -> Option<Ipv4Addr> {
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
let table = self.inner.route_table.read();
for (k, v) in table.iter() {
for route in v {
for (route, _) in v {
if &route.route_key() == route_key && route.is_p2p() {
return Some(*k);
}
@@ -429,44 +298,25 @@ impl Context {
None
}
pub fn need_punch(&self, id: &Ipv4Addr) -> bool {
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
if let Some(v) = table.get(id) {
if v.iter().filter(|k| k.is_p2p()).count() >= self.inner.channel_num {
if let Some(v) = self.inner.route_table.read().get(id) {
if v.iter().filter(|(k, _)| k.is_p2p()).count() >= self.inner.channel_num {
return false;
}
}
true
}
pub fn route_table(&self) -> Vec<(Ipv4Addr, Vec<Route>)> {
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
table.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
let table = self.inner.route_table.read();
table
.iter()
.map(|(k, v)| (k.clone(), v.iter().map(|(i, _)| *i).collect()))
.collect()
}
pub fn route_table_one(&self) -> Vec<(Ipv4Addr, Route)> {
let mut list = Vec::with_capacity(8);
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
for (k, v) in table {
if let Some(route) = v.first() {
let table = self.inner.route_table.read();
for (k, v) in table.iter() {
if let Some((route, _)) = v.first() {
list.push((*k, *route));
}
}
@@ -474,16 +324,9 @@ impl Context {
}
pub fn direct_route_table_one(&self) -> Vec<(Ipv4Addr, Route)> {
let mut list = Vec::with_capacity(8);
let guard = &crossbeam_epoch::pin();
let table = unsafe {
self.inner
.route_table
.load(Ordering::Relaxed, guard)
.as_ref()
.unwrap()
};
for (k, v) in table {
if let Some(route) = v.first() {
let table = self.inner.route_table.read();
for (k, v) in table.iter() {
if let Some((route, _)) = v.first() {
if route.metric == 1 {
list.push((*k, *route));
}
@@ -493,35 +336,20 @@ impl Context {
}
pub fn remove_route(&self, id: &Ipv4Addr, route_key: RouteKey) {
let guard = &crossbeam_epoch::pin();
let route_table = &self.inner.route_table;
let mut table_share = route_table.load(Ordering::Relaxed, guard);
loop {
let mut table = unsafe { table_share.as_ref().unwrap().clone() };
if let Some(routes) = table.get_mut(id) {
routes.retain(|x| x.route_key() != route_key);
match route_table.compare_exchange(
table_share,
Owned::new(table),
Ordering::Relaxed,
Ordering::Relaxed,
guard,
) {
Ok(p) => unsafe {
guard.defer_destroy(p);
self.inner.route_table_time.remove(&(route_key, *id));
return;
},
Err(e) => {
table_share = e.current;
}
}
}
if let Some(routes) = self.inner.route_table.write().get_mut(id) {
routes.retain(|(x, _)| x.route_key() != route_key);
} else {
return;
}
}
pub fn update_read_time(&self, id: &Ipv4Addr, route_key: &RouteKey) {
if let Some(mut time) = self.inner.route_table_time.get_mut(&(*route_key, *id)) {
*time.value_mut() = Instant::now();
if let Some(routes) = self.inner.route_table.read().get(id) {
for (route, time) in routes {
if &route.route_key() == route_key {
time.store(Instant::now());
break;
}
}
}
}
}
@@ -569,8 +397,8 @@ fn buf_channel_group(size: usize) -> (BufSenderGroup, BufReceiverGroup) {
}
impl Channel {
async fn tcp_handle(
mut tcp_r: OwnedReadHalf,
fn tcp_handle(
tcp_r: &mut TcpStream,
context: Context,
handler: ChannelDataHandler,
head_reserve: usize,
@@ -580,7 +408,7 @@ impl Channel {
let key = RouteKey::new(TCP_ID, addr);
loop {
let mut buf = [0; 4096];
tcp_r.read_exact(&mut head).await?;
tcp_r.read_exact(&mut head)?;
let len = (((head[2] as u16) << 8) | head[3] as u16) as usize;
if len < 12 || len > buf.len() {
return Err(io::Error::new(
@@ -588,82 +416,98 @@ impl Channel {
"length overflow",
));
}
tcp_r
.read_exact(&mut buf[head_reserve..head_reserve + len])
.await?;
tcp_r.read_exact(&mut buf[head_reserve..head_reserve + len])?;
handler.handle(&mut buf, head_reserve, head_reserve + len, key, &context);
}
}
async fn start_tcp(
mut worker: VntWorker,
tcp_stream: TcpStream,
mut receiver: tokio::sync::mpsc::Receiver<Vec<u8>>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
fn start_tcp(
worker: VntWorker,
mut tcp_stream: TcpStream,
receiver: std::sync::mpsc::Receiver<Vec<u8>>,
context: Context,
handler: ChannelDataHandler,
head_reserve: usize,
) {
let (tcp_r, mut tcp_w) = tcp_stream.into_split();
let current_device = context.inner.current_device.clone();
{
let mut tcp_r = tcp_stream.try_clone().unwrap();
let context = context.clone();
let handler = handler.clone();
tokio::spawn(async move {
if let Err(e) = Self::tcp_handle(tcp_r, context, handler, head_reserve).await {
log::info!("tcp链接断开:{:?}", e);
}
});
thread::Builder::new()
.name("tcp_reader".into())
.spawn(move || {
if let Err(e) = Self::tcp_handle(&mut tcp_r, context, handler, head_reserve) {
log::info!("tcp链接断开:{:?}", e);
}
if let Err(e) = tcp_r.shutdown(Shutdown::Both) {
log::info!("tcp链接关闭异常:{:?}", e);
}
})
.unwrap();
}
let mut head = [0; 4];
loop {
tokio::select! {
_=worker.stop_wait()=>{
let data = match receiver.recv() {
Ok(data) => data,
Err(_) => {
break;
}
rs=receiver.recv()=>{
if let Some(data) = rs{
let len = data.len();
head[2] = (len >> 8) as u8;
head[3] = (len & 0xFF) as u8;
let mut err = false;
if let Err(e) = tcp_w.write_all(&head).await{
err = true;
log::info!("发送失败,需要重连:{:?}",e);
}else if let Err(e) = tcp_w.write_all(&data).await{
err = true;
log::info!("发送失败,需要重连:{:?}",e);
}
if err {
let _ = tcp_w.shutdown().await;
match TcpStream::connect(current_device.load().connect_server).await {
Ok(tcp_stream) => {
let (r, w) = tcp_stream.into_split();
tcp_w = w;
let context = context.clone();
let handler = handler.clone();
tokio::spawn(async move {
if let Err(e) = Self::tcp_handle(r, context,handler, head_reserve).await {
log::info!("tcp 链接断开:{:?}",e);
}
});
};
let len = data.len();
if len == 0 {
break;
}
head[2] = (len >> 8) as u8;
head[3] = (len & 0xFF) as u8;
let mut err = false;
if let Err(e) = tcp_stream.write_all(&head) {
err = true;
log::info!("发送失败,需要重连:{:?}", e);
} else if let Err(e) = tcp_stream.write_all(&data) {
err = true;
log::info!("发送失败,需要重连:{:?}", e);
}
if err {
if let Err(e) = tcp_stream.shutdown(Shutdown::Both) {
log::info!("tcp链接关闭异常:{:?}", e);
}
match TcpStream::connect(current_device.load().connect_server) {
Ok(tcp) => {
tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
tcp_stream = tcp;
let mut tcp_r = tcp_stream.try_clone().unwrap();
let context = context.clone();
let handler = handler.clone();
thread::Builder::new()
.name("tcp_reader".into())
.spawn(move || {
if let Err(e) =
Self::tcp_handle(&mut tcp_r, context, handler, head_reserve)
{
log::info!("重连后 tcp链接断开:{:?}", e);
}
Err(e) => {
log::info!("重连失败:{:?}",e);
if let Err(e) = tcp_r.shutdown(Shutdown::Both) {
log::info!("重连后 tcp链接关闭异常:{:?}", e);
}
};
}
}else{
break;
})
.unwrap();
}
Err(e) => {
log::info!("重连失败:{:?}", e);
}
}
}
}
if let Err(e) = tcp_stream.shutdown(Shutdown::Both) {
log::info!("tcp链接关闭异常:{:?}", e);
}
worker.stop_all();
}
pub async fn start(
self,
mut worker: VntWorker,
tcp: Option<(TcpStream, tokio::sync::mpsc::Receiver<Vec<u8>>)>,
tcp: Option<(TcpStream, std::sync::mpsc::Receiver<Vec<u8>>)>,
head_reserve: usize, //头部预留字节
symmetric_channel_num: usize, //对称网络,则再加一组监听,提升打洞成功率
relay: bool,
@@ -678,7 +522,7 @@ impl Channel {
for buf_receiver in buf_receiver.0 {
let context = context.clone();
let handler = handler.clone();
std::thread::Builder::new()
thread::Builder::new()
.name(format!("recv-handler-{}", num))
.spawn(move || {
while let Ok((mut buf, start, end, route_key)) = buf_receiver.recv() {
@@ -694,33 +538,18 @@ impl Channel {
None
};
if let Some((tcp_stream, receiver)) = tcp {
tokio::spawn(Self::start_tcp(
worker.worker("main_channel_tcp"),
tcp_stream,
receiver,
context.inner.current_device.clone(),
context.clone(),
handler.clone(),
head_reserve,
));
}
if let Some(main_channel_ipv6) = &context.inner.main_channel_ipv6 {
let worker = worker.worker("main_channel_ipv6");
let context = context.clone();
let main_channel_ipv6 = main_channel_ipv6.clone();
let handler = handler.clone();
let buf_sender = buf_sender.clone();
std::thread::Builder::new()
.name("ipv6-recv".into())
let main_channel_tcp = worker.worker("main_channel_tcp");
thread::Builder::new()
.name("main_channel_tcp".into())
.spawn(move || {
log::info!("启动udp v6");
Self::main_start_(
worker,
Self::start_tcp(
main_channel_tcp,
tcp_stream,
receiver,
context,
UDP_V6_ID,
main_channel_ipv6,
handler,
buf_sender,
head_reserve,
)
})
@@ -732,7 +561,7 @@ impl Channel {
let main_channel = main_channel.clone();
let handler = handler.clone();
let buf_sender = buf_sender.clone();
std::thread::Builder::new()
thread::Builder::new()
.name("ipv4-recv".into())
.spawn(move || {
log::info!("启动udp v4");
+14 -9
View File
@@ -1,10 +1,11 @@
use crate::channel::channel::Context;
use crate::channel::RouteKey;
use std::io;
use std::io::{Error, ErrorKind};
use std::net::Ipv4Addr;
use std::time::Duration;
use crate::channel::channel::Context;
use crate::channel::RouteKey;
pub struct Idle {
read_idle: Duration,
context: Context,
@@ -21,13 +22,17 @@ impl Idle {
pub async fn next_idle(&self) -> io::Result<(Ipv4Addr, RouteKey)> {
loop {
let mut max = Duration::from_secs(0);
for entry in self.context.inner.route_table_time.iter() {
let last_read = entry.value().elapsed();
if last_read >= self.read_idle {
return Ok((entry.key().1.clone(), entry.key().0.clone()));
} else {
if max < last_read {
max = last_read;
{
for (ip, routes) in self.context.inner.route_table.read().iter() {
for (route, time) in routes {
let last_read = time.load().elapsed();
if last_read >= self.read_idle {
return Ok((*ip, route.route_key()));
} else {
if max < last_read {
max = last_read;
}
}
}
}
}
-1
View File
@@ -7,7 +7,6 @@ pub mod sender;
const TCP_ID: usize = 0;
const UDP_ID: usize = 1;
const UDP_V6_ID: usize = 2;
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum Status {
+108 -2
View File
@@ -15,8 +15,22 @@ use crate::cipher::openssl_aes_ecb::AesEcbCipher;
use crate::cipher::ring_aes_gcm_cipher::AesGcmCipher;
#[cfg(feature = "sm4_cbc")]
use crate::cipher::sm4_cbc::Sm4CbcCipher;
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
use crate::cipher::Finger;
use crate::protocol::NetPacket;
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
use sha2::Digest;
use std::io;
use std::str::FromStr;
@@ -38,6 +52,21 @@ impl FromStr for CipherModel {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
#[cfg(not(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
)))]
return Err(format!("not match '{}', no encrypt", s));
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
match s.to_lowercase().trim() {
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
"aes_gcm" => Ok(CipherModel::AesGcm),
@@ -49,7 +78,7 @@ impl FromStr for CipherModel {
"sm4_cbc" => Ok(CipherModel::Sm4Cbc),
_ => {
let mut enums = String::new();
#[cfg(feature = "aes_gcm")]
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
enums.push_str("/aes_gcm");
#[cfg(feature = "aes_cbc")]
enums.push_str("/aes_cbc");
@@ -80,8 +109,28 @@ pub enum Cipher {
Sm4Cbc(Sm4CbcCipher),
None,
}
impl Cipher {
#[cfg(not(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
)))]
pub fn new_password(
_model: CipherModel,
_password: Option<String>,
_token: Option<String>,
) -> Self {
Cipher::None
}
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
pub fn new_password(
model: CipherModel,
password: Option<String>,
@@ -134,6 +183,23 @@ impl Cipher {
Cipher::None
}
}
#[cfg(not(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
)))]
pub fn new_key(_key: [u8; 32], _token: String) -> io::Result<Self> {
Err(io::Error::new(io::ErrorKind::Other, "key error"))
}
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
pub fn new_key(key: [u8; 32], token: String) -> io::Result<Self> {
let finger = Some(Finger::new(&token));
match key.len() {
@@ -171,6 +237,26 @@ impl Cipher {
}
}
}
#[cfg(not(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
)))]
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
&self,
_net_packet: &mut NetPacket<B>,
) -> io::Result<()> {
Ok(())
}
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
&self,
net_packet: &mut NetPacket<B>,
@@ -187,6 +273,26 @@ impl Cipher {
Cipher::None => Ok(()),
}
}
#[cfg(not(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
)))]
pub fn check_finger<B: AsRef<[u8]> + AsMut<[u8]>>(
&self,
_net_packet: &NetPacket<B>,
) -> io::Result<()> {
Ok(())
}
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
pub fn check_finger<B: AsRef<[u8]>>(&self, net_packet: &NetPacket<B>) -> io::Result<()> {
match self {
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
+14
View File
@@ -7,6 +7,13 @@ mod aes_ecb;
#[cfg(not(feature = "ring-cipher"))]
mod aes_gcm_cipher;
mod cipher;
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
mod finger;
#[cfg(feature = "aes_ecb")]
#[cfg(any(feature = "openssl-vendored", feature = "openssl"))]
@@ -19,5 +26,12 @@ mod rsa_cipher;
mod sm4_cbc;
pub use cipher::Cipher;
pub use cipher::CipherModel;
#[cfg(any(
feature = "aes_gcm",
feature = "server_encrypt",
feature = "aes_cbc",
feature = "aes_ecb",
feature = "sm4_cbc"
))]
pub use finger::Finger;
pub use rsa_cipher::RsaCipher;
+3 -3
View File
@@ -8,7 +8,7 @@ use rand::Rng;
#[cfg(feature = "server_encrypt")]
use rsa::pkcs8::der::Decode;
#[cfg(feature = "server_encrypt")]
use rsa::{PublicKey, RsaPublicKey};
use rsa::RsaPublicKey;
#[cfg(feature = "server_encrypt")]
use sha2::Digest;
#[cfg(feature = "server_encrypt")]
@@ -46,7 +46,7 @@ impl RsaCipher {
#[cfg(feature = "server_encrypt")]
pub fn finger(&self) -> io::Result<String> {
match self.inner.public_key.to_public_key_der() {
Ok(der) => match rsa::pkcs8::SubjectPublicKeyInfo::from_der(der.as_bytes()) {
Ok(der) => match rsa::pkcs8::SubjectPublicKeyInfoRef::from_der(der.as_bytes()) {
Ok(spki) => match spki.fingerprint_base64() {
Ok(finger) => Ok(finger),
Err(e) => Err(io::Error::new(
@@ -109,7 +109,7 @@ impl RsaCipher {
secret_body.set_finger(&key[16..])?;
match self.inner.public_key.encrypt(
&mut rng,
rsa::PaddingScheme::PKCS1v15Encrypt,
rsa::pkcs1v15::Pkcs1v15Encrypt,
secret_body.buffer(),
) {
Ok(enc_data) => {
+44 -44
View File
@@ -1,14 +1,14 @@
use std::collections::HashMap;
use std::io;
use std::net::TcpStream;
use std::net::UdpSocket;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::sync::Arc;
use std::time::Duration;
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use parking_lot::Mutex;
use parking_lot::{Mutex, RwLock};
use rand::Rng;
use std::net::UdpSocket;
use tokio::net::TcpStream;
use tokio::sync::mpsc::channel;
use crate::channel::channel::{Channel, Context};
@@ -31,7 +31,6 @@ use crate::handle::{
CurrentDeviceInfo, PeerDeviceInfo,
};
use crate::igmp_server::IgmpServer;
use crate::ip_proxy::DashMapNew;
use crate::nat::NatTest;
use crate::tun_tap_device;
use crate::tun_tap_device::{DeviceReader, DeviceWriter};
@@ -52,13 +51,12 @@ pub struct Vnt {
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
nat_test: NatTest,
connect_status: Arc<AtomicCell<ConnectStatus>>,
peer_nat_info_map: Arc<DashMap<Ipv4Addr, NatInfo>>,
peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>>,
}
pub struct VntUtil {
config: Config,
main_channel: UdpSocket,
main_channel_ipv6: Option<UdpSocket>,
main_tcp_channel: Option<TcpStream>,
response: Option<RegResponse>,
iface: Option<(DeviceWriter, DeviceReader)>,
@@ -67,27 +65,17 @@ pub struct VntUtil {
}
impl VntUtil {
pub async fn new(config: Config) -> io::Result<VntUtil> {
pub fn new(config: Config) -> io::Result<VntUtil> {
let address: SocketAddr = format!("[::]:{}", config.port).parse().unwrap();
//单个udp用同步的性能更好,但是代理和多端口监听用异步更方便,这里将两者结合起来
let main_channel = UdpSocket::bind(format!("0.0.0.0:{}", config.port))?;
let socket = socket2::Socket::new(socket2::Domain::IPV6, socket2::Type::DGRAM, None)?;
socket.set_only_v6(false)?;
socket.bind(&address.into())?;
let main_channel: UdpSocket = socket.into();
main_channel.set_write_timeout(Some(Duration::from_secs(5)))?;
main_channel.set_read_timeout(Some(Duration::from_secs(2)))?;
let main_channel_ipv6 = if config.punch_model != PunchModel::IPv4 {
match UdpSocket::bind(format!("[::]:{}", config.port)) {
Ok(main_channel_ipv6) => {
main_channel_ipv6.set_write_timeout(Some(Duration::from_secs(5)))?;
Some(main_channel_ipv6)
}
Err(e) => {
log::warn!("绑定ipv6地址失败:{}", e);
None
}
}
} else {
None
};
let server_cipher = if config.server_encrypt {
let mut key = [0 as u8; 32];
let mut key = [0u8; 32];
rand::thread_rng().fill(&mut key);
Cipher::new_key(key, config.token.clone())?
} else {
@@ -96,7 +84,6 @@ impl VntUtil {
Ok(VntUtil {
config,
main_channel,
main_channel_ipv6,
main_tcp_channel: None,
response: None,
iface: None,
@@ -105,28 +92,28 @@ impl VntUtil {
})
}
///链接
pub async fn connect(&mut self) -> io::Result<()> {
pub fn connect(&mut self) -> io::Result<()> {
if self.config.tcp {
let tcp = TcpStream::connect(self.config.server_address).await?;
let tcp = TcpStream::connect(self.config.server_address)?;
tcp.set_read_timeout(Some(Duration::from_secs(10)))?;
let _ = self.main_tcp_channel.insert(tcp);
}
Ok(())
}
///握手 用于获取公钥
pub async fn handshake(&mut self) -> Result<Option<RsaCipher>, HandshakeEnum> {
pub fn handshake(&mut self) -> Result<Option<RsaCipher>, HandshakeEnum> {
let rsa_cipher = handshake_handler::handshake(
&self.main_channel,
self.main_tcp_channel.as_mut(),
self.config.server_address,
self.config.server_encrypt,
)
.await?;
)?;
self.rsa_cipher = rsa_cipher.clone();
Ok(rsa_cipher)
}
/// 加密握手 用于同步密钥
pub async fn secret_handshake(&mut self) -> Result<(), HandshakeEnum> {
pub fn secret_handshake(&mut self) -> Result<(), HandshakeEnum> {
handshake_handler::secret_handshake(
&self.main_channel,
self.main_tcp_channel.as_mut(),
@@ -135,10 +122,9 @@ impl VntUtil {
&self.server_cipher,
self.config.token.clone(),
)
.await
}
/// 注册
pub async fn register(&mut self) -> Result<RegResponse, ReqEnum> {
pub fn register(&mut self) -> Result<RegResponse, ReqEnum> {
match registration_handler::registration(
&self.main_channel,
self.main_tcp_channel.as_mut(),
@@ -149,9 +135,7 @@ impl VntUtil {
self.config.name.clone(),
self.config.ip.unwrap_or(Ipv4Addr::UNSPECIFIED),
self.config.password.is_some(),
)
.await
{
) {
Ok(res) => {
let _ = self.response.insert(res.clone());
Ok(res)
@@ -253,17 +237,17 @@ impl VntUtil {
let (cone_sender, cone_receiver) = channel(3);
let (symmetric_sender, symmetric_receiver) = channel(2);
let (tcp_sender, tcp) = if let Some(main_tcp_channel) = self.main_tcp_channel {
let (tcp_sender, tcp_receiver) = channel::<Vec<u8>>(100);
let (tcp_sender, tcp_receiver) = std::sync::mpsc::sync_channel::<Vec<u8>>(100);
(Some(tcp_sender), Some((main_tcp_channel, tcp_receiver)))
} else {
(None, None)
};
let context = Context::new(
Arc::new(self.main_channel),
self.main_channel_ipv6.map(|v| Arc::new(v)),
tcp_sender,
current_device.clone(),
1,
config.first_latency,
);
let punch = Punch::new(context.clone(), config.punch_model);
let idle = Idle::new(Duration::from_secs(16), context.clone());
@@ -280,15 +264,15 @@ impl VntUtil {
));
let device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>> =
Arc::new(Mutex::new((response.epoch, response.device_info_list)));
let peer_nat_info_map: Arc<DashMap<Ipv4Addr, NatInfo>> = Arc::new(DashMap::new0());
let peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>> =
Arc::new(RwLock::new(HashMap::with_capacity(16)));
let connect_status = Arc::new(AtomicCell::new(ConnectStatus::Connected));
let public_ip = response.public_ip;
let public_port = response.public_port;
let local_port = context.main_local_ipv4_port().unwrap_or(0);
let local_port = context.main_local_udp_port().unwrap_or(0);
let local_ipv4_addr = crate::nat::local_ipv4_addr(local_port);
let ipv6_port = context.main_local_ipv6_port().unwrap_or(0);
let ipv6_addr = crate::nat::local_ipv6_addr(ipv6_port);
let ipv6_addr = crate::nat::local_ipv6_addr(local_port);
// NAT检测
let nat_test = NatTest::new(
config.stun_server.clone(),
@@ -302,7 +286,8 @@ impl VntUtil {
} else {
Some(ExternalRoute::new(config.in_ips))
};
let (tcp_proxy, udp_proxy, ip_proxy_map) = if config.out_ips.is_empty() {
#[cfg(feature = "ip_proxy")]
let (tcp_proxy, udp_proxy, ip_proxy_map) = if config.out_ips.is_empty() || config.no_proxy {
(None, None, None)
} else {
let (tcp_proxy, udp_proxy, ip_proxy_map) = crate::ip_proxy::init_proxy(
@@ -333,6 +318,7 @@ impl VntUtil {
igmp_server.clone(),
current_device.clone(),
in_external_route,
#[cfg(feature = "ip_proxy")]
ip_proxy_map.clone(),
client_cipher.clone(),
self.server_cipher.clone(),
@@ -347,6 +333,7 @@ impl VntUtil {
igmp_server.clone(),
current_device.clone(),
in_external_route,
#[cfg(feature = "ip_proxy")]
ip_proxy_map.clone(),
client_cipher.clone(),
self.server_cipher.clone(),
@@ -362,6 +349,7 @@ impl VntUtil {
igmp_server.clone(),
current_device.clone(),
in_external_route,
#[cfg(feature = "ip_proxy")]
ip_proxy_map.clone(),
client_cipher.clone(),
self.server_cipher.clone(),
@@ -378,6 +366,7 @@ impl VntUtil {
device_writer.clone(),
connect_status.clone(),
peer_nat_info_map.clone(),
#[cfg(feature = "ip_proxy")]
ip_proxy_map,
out_external_route,
cone_sender,
@@ -452,6 +441,7 @@ impl VntUtil {
));
}
}
#[cfg(feature = "ip_proxy")]
{
//代理
if let Some(tcp_proxy) = tcp_proxy {
@@ -460,6 +450,8 @@ impl VntUtil {
if let Some(udp_proxy) = udp_proxy {
tokio::spawn(udp_proxy.start());
}
}
{
let context = context.clone();
let nat_test = nat_test.clone();
tokio::spawn(async move {
@@ -497,7 +489,7 @@ impl Vnt {
self.current_device.load()
}
pub fn peer_nat_info(&self, ip: &Ipv4Addr) -> Option<NatInfo> {
self.peer_nat_info_map.get(ip).map(|e| e.value().clone())
self.peer_nat_info_map.read().get(ip).cloned()
}
pub fn connection_status(&self) -> ConnectStatus {
self.connect_status.load()
@@ -572,12 +564,15 @@ pub struct Config {
pub tcp: bool,
pub ip: Option<Ipv4Addr>,
pub relay: bool,
#[cfg(feature = "ip_proxy")]
pub no_proxy: bool,
pub server_encrypt: bool,
pub parallel: usize,
pub cipher_model: CipherModel,
pub finger: bool,
pub punch_model: PunchModel,
pub port: u16,
pub first_latency: bool,
}
impl Config {
@@ -597,12 +592,14 @@ impl Config {
tcp: bool,
ip: Option<Ipv4Addr>,
relay: bool,
#[cfg(feature = "ip_proxy")] no_proxy: bool,
server_encrypt: bool,
parallel: usize,
cipher_model: CipherModel,
finger: bool,
punch_model: PunchModel,
port: u16,
first_latency: bool,
) -> Self {
for x in stun_server.iter_mut() {
if !x.contains(":") {
@@ -625,12 +622,15 @@ impl Config {
tcp,
ip,
relay,
#[cfg(feature = "ip_proxy")]
no_proxy,
server_encrypt,
parallel,
cipher_model,
finger,
punch_model,
port,
first_latency,
}
}
}
+5 -5
View File
@@ -22,20 +22,20 @@ impl VntUtilSync {
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
let vnt_util = runtime.block_on(VntUtil::new(config))?;
let vnt_util = VntUtil::new(config)?;
Ok(VntUtilSync { vnt_util, runtime })
}
pub fn connect(&mut self) -> io::Result<()> {
self.runtime.block_on(self.vnt_util.connect())
self.vnt_util.connect()
}
pub fn handshake(&mut self) -> Result<Option<RsaCipher>, HandshakeEnum> {
self.runtime.block_on(self.vnt_util.handshake())
self.vnt_util.handshake()
}
pub fn secret_handshake(&mut self) -> Result<(), HandshakeEnum> {
self.runtime.block_on(self.vnt_util.secret_handshake())
self.vnt_util.secret_handshake()
}
pub fn register(&mut self) -> Result<RegResponse, ReqEnum> {
self.runtime.block_on(self.vnt_util.register())
self.vnt_util.register()
}
#[cfg(any(target_os = "android"))]
pub fn create_iface(&mut self, vpn_fd: i32) {
+3
View File
@@ -37,6 +37,9 @@ impl AllowExternalRoute {
}
}
pub fn allow(&self, ip: &Ipv4Addr) -> bool {
if self.route_table.is_empty() {
return false;
}
let ip = u32::from_be_bytes(ip.octets());
for (dest, mask) in self.route_table.iter() {
if *mask & ip == *mask & *dest {
+26 -20
View File
@@ -1,9 +1,4 @@
use std::net::SocketAddr;
use protobuf::Message;
use std::net::UdpSocket;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use std::net::{SocketAddr, SocketAddrV6};
use crate::channel::channel::Context;
use crate::channel::RouteKey;
@@ -11,6 +6,10 @@ use crate::cipher::{Cipher, RsaCipher};
use crate::proto::message::{HandshakeRequest, HandshakeResponse, SecretHandshakeRequest};
use crate::protocol::body::RSA_ENCRYPTION_RESERVED;
use crate::protocol::{service_packet, NetPacket, Protocol, Version, MAX_TTL};
use protobuf::Message;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::net::UdpSocket;
pub enum HandshakeEnum {
NotSecret,
@@ -59,7 +58,7 @@ fn secret_handshake_request_packet(
}
/// 第一次握手,拿到公钥
pub async fn handshake(
pub fn handshake(
main_channel: &UdpSocket,
main_tcp_channel: Option<&mut TcpStream>,
server_address: SocketAddr,
@@ -74,8 +73,7 @@ pub async fn handshake(
server_address,
send_buf,
&mut recv_buf,
)
.await?;
)?;
let net_packet = match NetPacket::new(&recv_buf[..len]) {
Ok(net_packet) => net_packet,
Err(e) => {
@@ -140,7 +138,7 @@ pub async fn handshake(
}
}
async fn send_recv(
fn send_recv(
main_channel: &UdpSocket,
main_tcp_channel: Option<&mut TcpStream>,
server_address: SocketAddr,
@@ -152,34 +150,43 @@ async fn send_recv(
let len = send_buf.len();
head[2] = (len >> 8) as u8;
head[3] = (len & 0xFF) as u8;
if let Err(e) = main_tcp_channel.write_all(&head).await {
if let Err(e) = main_tcp_channel.write_all(&head) {
return Err(HandshakeEnum::Other(format!("send error:{}", e)));
}
if let Err(e) = main_tcp_channel.write_all(send_buf).await {
if let Err(e) = main_tcp_channel.write_all(send_buf) {
return Err(HandshakeEnum::Other(format!("send error:{}", e)));
}
if let Err(e) = main_tcp_channel.read_exact(&mut head).await {
if let Err(e) = main_tcp_channel.read_exact(&mut head) {
return Err(HandshakeEnum::Other(format!("read error:{}", e)));
}
let len = (((head[2] as u16) << 8) | head[3] as u16) as usize;
if len > recv_buf.len() {
return Err(HandshakeEnum::Other("too long".to_string()));
}
if let Err(e) = main_tcp_channel.read_exact(&mut recv_buf[..len]).await {
if let Err(e) = main_tcp_channel.read_exact(&mut recv_buf[..len]) {
return Err(HandshakeEnum::Other(format!("read error:{}", e)));
}
Ok(len)
} else {
let server_address = if let SocketAddr::V4(ipv4) = server_address {
SocketAddr::V6(SocketAddrV6::new(
ipv4.ip().to_ipv6_mapped(),
ipv4.port(),
0,
0,
))
} else {
server_address
};
if let Err(e) = main_channel.send_to(send_buf, server_address) {
return Err(HandshakeEnum::Other(format!("send error:{}", e)));
}
match main_channel.recv_from(recv_buf) {
Ok((len, addr)) => {
if server_address != addr {
Err(HandshakeEnum::Other(format!("invalid data,from {}", addr)))
} else {
Ok(len)
log::warn!("请求{:?}和响应{:?}地址不一致", server_address, addr);
}
Ok(len)
}
Err(e) => Err(HandshakeEnum::Other(format!("receiver error:{}", e))),
}
@@ -187,7 +194,7 @@ async fn send_recv(
}
/// 第二次握手,同步对称密钥,后续将使用对称加密
pub async fn secret_handshake(
pub fn secret_handshake(
main_channel: &UdpSocket,
main_tcp_channel: Option<&mut TcpStream>,
server_address: SocketAddr,
@@ -213,8 +220,7 @@ pub async fn secret_handshake(
server_address,
send_buf,
&mut recv_buf,
)
.await?;
)?;
let mut net_packet = match NetPacket::new(&mut recv_buf[..len]) {
Ok(net_packet) => net_packet,
Err(e) => {
+5 -4
View File
@@ -3,15 +3,15 @@ use std::net::{Ipv4Addr, ToSocketAddrs};
use std::sync::Arc;
use std::time::Duration;
use crossbeam_utils::atomic::AtomicCell;
use parking_lot::Mutex;
use rand::prelude::SliceRandom;
use crate::channel::idle::Idle;
use crate::channel::sender::ChannelSender;
use crate::channel::Route;
use crate::cipher::Cipher;
use crate::core::status::VntWorker;
use crossbeam_utils::atomic::AtomicCell;
use parking_lot::Mutex;
use rand::prelude::SliceRandom;
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
use crate::protocol::body::ENCRYPTION_RESERVED;
use crate::protocol::control_packet::PingPacket;
@@ -64,6 +64,7 @@ pub fn start_heartbeat(
worker.stop_all();
});
}
pub fn start_heartbeat_main(
mut worker: VntWorker,
sender: ChannelSender,
+21 -103
View File
@@ -1,10 +1,10 @@
use std::collections::HashMap;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6};
use std::sync::Arc;
use std::time::{Duration, Instant};
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use parking_lot::Mutex;
use parking_lot::{Mutex, RwLock};
use protobuf::Message;
use tokio::sync::mpsc::Sender;
@@ -22,7 +22,8 @@ use crate::handle::handshake_handler::secret_handshake_req;
use crate::handle::registration_handler::Register;
use crate::handle::{ConnectStatus, CurrentDeviceInfo, PeerDeviceInfo, PeerDeviceStatus};
use crate::igmp_server::IgmpServer;
use crate::ip_proxy::IpProxyMap;
#[cfg(feature = "ip_proxy")]
use crate::ip_proxy::{IpProxyMap, ProxyHandler};
use crate::nat;
use crate::nat::NatTest;
use crate::proto::message::{DeviceList, PunchInfo, PunchNatType, RegistrationResponse};
@@ -44,7 +45,8 @@ pub struct ChannelDataHandler {
igmp_server: Option<IgmpServer>,
device_writer: DeviceWriter,
connect_status: Arc<AtomicCell<ConnectStatus>>,
peer_nat_info_map: Arc<DashMap<Ipv4Addr, NatInfo>>,
peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>>,
#[cfg(feature = "ip_proxy")]
ip_proxy_map: Option<IpProxyMap>,
out_external_route: AllowExternalRoute,
cone_sender: Sender<(Ipv4Addr, NatInfo)>,
@@ -66,8 +68,8 @@ impl ChannelDataHandler {
igmp_server: Option<IgmpServer>,
device_writer: DeviceWriter,
connect_status: Arc<AtomicCell<ConnectStatus>>,
peer_nat_info_map: Arc<DashMap<Ipv4Addr, NatInfo>>,
ip_proxy_map: Option<IpProxyMap>,
peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>>,
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
out_external_route: AllowExternalRoute,
cone_sender: Sender<(Ipv4Addr, NatInfo)>,
symmetric_sender: Sender<(Ipv4Addr, NatInfo)>,
@@ -86,6 +88,7 @@ impl ChannelDataHandler {
device_writer,
connect_status,
peer_nat_info_map,
#[cfg(feature = "ip_proxy")]
ip_proxy_map,
out_external_route,
cone_sender,
@@ -225,109 +228,22 @@ impl ChannelDataHandler {
_ => {}
}
if not_broadcast && ipv4.destination_ip() != destination {
if let Some(ip_proxy_map) = &self.ip_proxy_map {
if self.out_external_route.allow(&ipv4.destination_ip()) {
match ipv4.protocol() {
ipv4::protocol::Protocol::Tcp => {
let dest_ip = ipv4.destination_ip();
//转发到代理目标地址
let mut tcp_packet = packet::tcp::tcp::TcpPacket::new(
source,
destination,
ipv4.payload_mut(),
)?;
let source_port = tcp_packet.source_port();
let dest_port = tcp_packet.destination_port();
tcp_packet
.set_destination_port(ip_proxy_map.tcp_proxy_port);
tcp_packet.update_checksum();
ipv4.set_destination_ip(destination);
ipv4.update_checksum();
let key = SocketAddrV4::new(source, source_port);
//https://github.com/crossbeam-rs/crossbeam/issues/1023
ip_proxy_map
.tcp_proxy_map
.insert(key, SocketAddrV4::new(dest_ip, dest_port));
}
ipv4::protocol::Protocol::Udp => {
let dest_ip = ipv4.destination_ip();
//转发到代理目标地址
let mut udp_packet = packet::udp::udp::UdpPacket::new(
source,
destination,
ipv4.payload_mut(),
)?;
let source_port = udp_packet.source_port();
let dest_port = udp_packet.destination_port();
udp_packet
.set_destination_port(ip_proxy_map.udp_proxy_port);
udp_packet.update_checksum();
ipv4.set_destination_ip(destination);
ipv4.update_checksum();
let key = SocketAddrV4::new(source, source_port);
ip_proxy_map
.udp_proxy_map
.insert(key, SocketAddrV4::new(dest_ip, dest_port));
}
#[cfg(not(target_os = "android"))]
ipv4::protocol::Protocol::Icmp => {
let dest_ip = ipv4.destination_ip();
//转发到代理目标地址
let icmp_packet =
icmp::IcmpPacket::new(ipv4.payload())?;
match icmp_packet.header_other() {
icmp::HeaderOther::Identifier(id, seq) => {
ip_proxy_map
.icmp_proxy_map
.insert((dest_ip, id, seq), source);
ip_proxy_map
.send_icmp(ipv4.payload(), &dest_ip)?;
}
_ => {
log::warn!(
"不支持的ip代理Icmp协议:{}->{}->{}",
source,
destination,
dest_ip
);
return Err(Error::Warn(
"不支持的ip代理Icmp协议".to_string(),
));
}
}
}
_ => {
log::warn!(
"不支持的ip代理ipv4协议{:?}:{}->{}->{}",
ipv4.protocol(),
source,
destination,
ipv4.destination_ip()
);
return Err(Error::Warn(
"不支持的ip代理ipv4协议".to_string(),
));
}
if self.out_external_route.allow(&ipv4.destination_ip()) {
#[cfg(feature = "ip_proxy")]
if let Some(ip_proxy_map) = &self.ip_proxy_map {
if ip_proxy_map.recv_handle(&mut ipv4, source, destination)? {
return Ok(());
}
} else {
log::warn!(
"没有ip代理规则{:?}:{}->{}->{}",
ipv4.protocol(),
source,
destination,
ipv4.destination_ip()
);
return Err(Error::Warn("没有ip代理规则".to_string()));
}
} else {
log::warn!(
"不支持ip代理{:?}:{}->{}->{}",
"没有ip代理规则{:?}:{}->{}->{}",
ipv4.protocol(),
source,
destination,
ipv4.destination_ip()
);
return Err(Error::Warn("不支持ip代理".to_string()));
return Err(Error::Warn("没有ip代理规则".to_string()));
}
}
@@ -503,7 +419,10 @@ impl ChannelDataHandler {
ipv6_addr,
punch_info.nat_type.enum_value_or_default().into(),
);
self.peer_nat_info_map.insert(source, peer_nat_info.clone());
{
let peer_nat_info = peer_nat_info.clone();
self.peer_nat_info_map.write().insert(source, peer_nat_info);
}
if !punch_info.reply {
let mut punch_reply = PunchInfo::new();
punch_reply.reply = true;
@@ -673,9 +592,8 @@ impl ChannelDataHandler {
.build()
.unwrap()
.block_on(async move {
let local_port = context.main_local_ipv4_port().unwrap_or(0);
let local_port = context.main_local_udp_port().unwrap_or(0);
let local_ipv4_addr = nat::local_ipv4_addr(local_port);
let local_port = context.main_local_ipv6_port().unwrap_or(0);
let ipv6_addr = nat::local_ipv6_addr(local_port);
let nat_info = nat_test
.re_test(
+17 -8
View File
@@ -1,14 +1,14 @@
use crossbeam_utils::atomic::AtomicCell;
use std::net::{Ipv4Addr, SocketAddr};
use std::io::{Read, Write};
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV6};
use std::time::{Duration, Instant};
use crate::channel::sender::ChannelSender;
use crate::cipher::Cipher;
use crate::handle::PeerDeviceInfo;
use protobuf::Message;
use std::net::TcpStream;
use std::net::UdpSocket;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use crate::proto::message::{RegistrationRequest, RegistrationResponse};
use crate::protocol::body::ENCRYPTION_RESERVED;
@@ -37,7 +37,7 @@ pub struct RegResponse {
}
///向中继服务器注册,token标识一个虚拟网关,device_id防止多次注册时得到的ip不一致
pub async fn registration(
pub fn registration(
main_channel: &UdpSocket,
main_tcp_channel: Option<&mut TcpStream>,
server_cipher: &Cipher,
@@ -67,28 +67,37 @@ pub async fn registration(
vec[2] = (len >> 8) as u8;
vec[3] = (len & 0xFF) as u8;
vec[4..].copy_from_slice(buf);
if let Err(e) = main_tcp_channel.write_all(&vec).await {
if let Err(e) = main_tcp_channel.write_all(&vec) {
return Err(ReqEnum::Other(format!("send error:{}", e)));
}
if let Err(e) = main_tcp_channel.read_exact(&mut recv_buf[..4]).await {
if let Err(e) = main_tcp_channel.read_exact(&mut recv_buf[..4]) {
return Err(ReqEnum::Other(format!("read error:{}", e)));
}
let len = 4 + (((recv_buf[2] as u16) << 8) | recv_buf[3] as u16) as usize;
if len > recv_buf.len() {
return Err(ReqEnum::Other("too long".to_string()));
}
if let Err(e) = main_tcp_channel.read_exact(&mut recv_buf[4..len]).await {
if let Err(e) = main_tcp_channel.read_exact(&mut recv_buf[4..len]) {
return Err(ReqEnum::Other(format!("read error:{}", e)));
}
&mut recv_buf[4..len]
} else {
let server_address = match server_address {
SocketAddr::V4(ipv4) => SocketAddr::V6(SocketAddrV6::new(
ipv4.ip().to_ipv6_mapped(),
ipv4.port(),
0,
0,
)),
SocketAddr::V6(_) => server_address,
};
if let Err(e) = main_channel.send_to(buf, server_address) {
return Err(ReqEnum::Other(format!("send error:{}", e)));
}
match main_channel.recv_from(&mut recv_buf) {
Ok((len, addr)) => {
if server_address != addr {
return Err(ReqEnum::Other(format!("invalid data,from {}", addr)));
log::warn!("请求{:?}和响应{:?}地址不一致", server_address, addr);
}
&mut recv_buf[..len]
}
+18 -70
View File
@@ -1,22 +1,23 @@
use std::net::Ipv4Addr;
use std::sync::Arc;
use parking_lot::RwLock;
use packet::ip::ipv4::packet::IpV4Packet;
use packet::ip::ipv4::protocol::Protocol;
use crate::channel::sender::ChannelSender;
use crate::cipher::Cipher;
use crate::error::*;
use crate::external_route::ExternalRoute;
use crate::handle::{check_dest, CurrentDeviceInfo};
use crate::igmp_server::{IgmpServer, Multicast};
use crate::ip_proxy::IpProxyMap;
#[cfg(feature = "ip_proxy")]
use crate::ip_proxy::{IpProxyMap, ProxyHandler};
use crate::protocol;
use crate::protocol::body::ENCRYPTION_RESERVED;
use crate::protocol::ip_turn_packet::BroadcastPacket;
use crate::protocol::{ip_turn_packet, NetPacket, Version, MAX_TTL};
use packet::ip::ipv4::packet::IpV4Packet;
use packet::ip::ipv4::protocol::Protocol;
use packet::tcp::tcp::TcpPacket;
use packet::udp::udp::UdpPacket;
use parking_lot::RwLock;
use std::io;
use std::net::{Ipv4Addr, SocketAddrV4};
use std::sync::Arc;
pub mod channel_group;
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
@@ -64,10 +65,8 @@ fn broadcast(
if peer_ips.is_empty() {
sender.send_main(net_packet.buffer(), current_device.connect_server)?;
} else {
let buf = vec![
0 as u8;
12 + 1 + peer_ips.len() * 4 + net_packet.data_len() + ENCRYPTION_RESERVED
];
let buf =
vec![0u8; 12 + 1 + peer_ips.len() * 4 + net_packet.data_len() + ENCRYPTION_RESERVED];
//剩余的发送到服务端,需要告知哪些已发送过
let mut server_packet = NetPacket::new_encrypt(buf)?;
server_packet.set_version(Version::V1);
@@ -99,16 +98,12 @@ pub fn base_handle(
igmp_server: &Option<IgmpServer>,
current_device: CurrentDeviceInfo,
ip_route: &Option<ExternalRoute>,
proxy_map: &Option<IpProxyMap>,
#[cfg(feature = "ip_proxy")] proxy_map: &Option<IpProxyMap>,
client_cipher: &Cipher,
server_cipher: &Cipher,
) -> Result<()> {
let ipv4_packet = IpV4Packet::new(&buf[12..data_len])?;
let protocol = ipv4_packet.protocol();
let ip_head_len = ipv4_packet.header_len() as usize * 4;
if 12 + ip_head_len >= data_len {
Err(io::Error::new(io::ErrorKind::Other, "ip_head_len err"))?
}
let src_ip = ipv4_packet.source_ip();
let mut dest_ip = ipv4_packet.destination_ip();
let mut net_packet = NetPacket::new0(data_len, buf)?;
@@ -190,58 +185,11 @@ pub fn base_handle(
} else {
return Ok(());
}
} else if let Some(proxy_map) = proxy_map {
match protocol {
Protocol::Tcp => {
let dest_addr = {
let tcp_packet = TcpPacket::new(
src_ip,
dest_ip,
&mut net_packet.payload_mut()[ip_head_len..],
)?;
SocketAddrV4::new(dest_ip, tcp_packet.destination_port())
};
if let Some(entry) = proxy_map.tcp_proxy_map.get(&dest_addr) {
let source_addr = entry.value();
let source_ip = *source_addr.ip();
let mut tcp_packet = TcpPacket::new(
source_ip,
dest_ip,
&mut net_packet.payload_mut()[ip_head_len..],
)?;
tcp_packet.set_source_port(source_addr.port());
tcp_packet.update_checksum();
let mut ipv4_packet = IpV4Packet::new(net_packet.payload_mut())?;
ipv4_packet.set_source_ip(source_ip);
ipv4_packet.update_checksum();
}
}
Protocol::Udp => {
let dest_addr = {
let udp_packet = UdpPacket::new(
src_ip,
dest_ip,
&mut net_packet.payload_mut()[ip_head_len..],
)?;
SocketAddrV4::new(dest_ip, udp_packet.destination_port())
};
if let Some(entry) = proxy_map.udp_proxy_map.get(&dest_addr) {
let source_addr = entry.value();
let source_ip = *source_addr.ip();
let mut udp_packet = UdpPacket::new(
source_ip,
dest_ip,
&mut net_packet.payload_mut()[ip_head_len..],
)?;
udp_packet.set_source_port(source_addr.port());
udp_packet.update_checksum();
let mut ipv4_packet = IpV4Packet::new(net_packet.payload_mut())?;
ipv4_packet.set_source_ip(source_ip);
ipv4_packet.update_checksum();
}
}
_ => {}
}
}
#[cfg(feature = "ip_proxy")]
if let Some(proxy_map) = proxy_map {
let mut ipv4_packet = IpV4Packet::new(net_packet.payload_mut())?;
proxy_map.send_handle(&mut ipv4_packet)?;
}
client_cipher.encrypt_ipv4(&mut net_packet)?;
//优先发到直连到地址
+9 -6
View File
@@ -18,6 +18,7 @@ use crate::external_route::ExternalRoute;
use crate::handle::tun_tap::channel_group::{buf_channel_group, BufSenderGroup};
use crate::handle::CurrentDeviceInfo;
use crate::igmp_server::IgmpServer;
#[cfg(feature = "ip_proxy")]
use crate::ip_proxy::IpProxyMap;
use crate::tun_tap_device::{DeviceReader, DeviceWriter};
@@ -29,7 +30,7 @@ pub fn start(
igmp_server: Option<IgmpServer>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
ip_route: Option<ExternalRoute>,
ip_proxy_map: Option<IpProxyMap>,
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
parallel: usize,
@@ -45,6 +46,7 @@ pub fn start(
igmp_server,
current_device,
ip_route,
#[cfg(feature = "ip_proxy")]
ip_proxy_map,
client_cipher,
server_cipher,
@@ -64,6 +66,7 @@ pub fn start(
let igmp_server = igmp_server.clone();
let current_device = current_device.clone();
let ip_route = ip_route.clone();
#[cfg(feature = "ip_proxy")]
let ip_proxy_map = ip_proxy_map.clone();
let client_cipher = client_cipher.clone();
let server_cipher = server_cipher.clone();
@@ -77,6 +80,7 @@ pub fn start(
&device_writer,
&sender,
&ip_route,
#[cfg(feature = "ip_proxy")]
&ip_proxy_map,
&client_cipher,
&server_cipher,
@@ -133,7 +137,7 @@ fn start_simple(
igmp_server: Option<IgmpServer>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
ip_route: Option<ExternalRoute>,
ip_proxy_map: Option<IpProxyMap>,
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
) -> io::Result<()> {
@@ -151,6 +155,7 @@ fn start_simple(
device_writer,
sender,
&ip_route,
#[cfg(feature = "ip_proxy")]
&ip_proxy_map,
&client_cipher,
&server_cipher,
@@ -168,7 +173,7 @@ fn handle(
device_writer: &DeviceWriter,
sender: &ChannelSender,
ip_route: &Option<ExternalRoute>,
proxy_map: &Option<IpProxyMap>,
#[cfg(feature = "ip_proxy")] proxy_map: &Option<IpProxyMap>,
client_cipher: &Cipher,
server_cipher: &Cipher,
) -> crate::Result<()> {
@@ -213,9 +218,6 @@ fn handle(
ethernet::protocol::Protocol::Ipv4 => {
let mut ipv4_packet = IpV4Packet::unchecked(ethernet_packet.payload_mut());
let src_ip = ipv4_packet.source_ip();
if src_ip != current_device.virtual_ip() {
return Ok(());
}
let dest_ip = ipv4_packet.destination_ip();
let protocol = ipv4_packet.protocol();
if src_ip == dest_ip {
@@ -244,6 +246,7 @@ fn handle(
igmp_server,
current_device,
ip_route,
#[cfg(feature = "ip_proxy")]
proxy_map,
client_cipher,
server_cipher,
+10 -11
View File
@@ -16,6 +16,7 @@ use crate::external_route::ExternalRoute;
use crate::handle::tun_tap::channel_group::{buf_channel_group, BufSenderGroup};
use crate::handle::CurrentDeviceInfo;
use crate::igmp_server::IgmpServer;
#[cfg(feature = "ip_proxy")]
use crate::ip_proxy::IpProxyMap;
use crate::tun_tap_device::{DeviceReader, DeviceWriter};
fn icmp(device_writer: &DeviceWriter, mut ipv4_packet: IpV4Packet<&mut [u8]>) -> Result<()> {
@@ -44,20 +45,13 @@ fn handle(
igmp_server: &Option<IgmpServer>,
current_device: CurrentDeviceInfo,
ip_route: &Option<ExternalRoute>,
proxy_map: &Option<IpProxyMap>,
#[cfg(feature = "ip_proxy")] proxy_map: &Option<IpProxyMap>,
client_cipher: &Cipher,
server_cipher: &Cipher,
) -> Result<()> {
let ipv4_packet = if let Ok(ipv4_packet) = IpV4Packet::new(&mut data[12..len]) {
ipv4_packet
} else {
return Ok(());
};
let ipv4_packet = IpV4Packet::new(&mut data[12..len])?;
let src_ip = ipv4_packet.source_ip();
let dest_ip = ipv4_packet.destination_ip();
if src_ip != current_device.virtual_ip() {
return Ok(());
}
if src_ip == dest_ip {
return icmp(&device_writer, ipv4_packet);
}
@@ -68,6 +62,7 @@ fn handle(
igmp_server,
current_device,
ip_route,
#[cfg(feature = "ip_proxy")]
proxy_map,
client_cipher,
server_cipher,
@@ -82,7 +77,7 @@ pub fn start(
igmp_server: Option<IgmpServer>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
ip_route: Option<ExternalRoute>,
ip_proxy_map: Option<IpProxyMap>,
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
parallel: usize,
@@ -98,6 +93,7 @@ pub fn start(
igmp_server,
current_device,
ip_route,
#[cfg(feature = "ip_proxy")]
ip_proxy_map,
client_cipher,
server_cipher,
@@ -117,6 +113,7 @@ pub fn start(
let igmp_server = igmp_server.clone();
let current_device = current_device.clone();
let ip_route = ip_route.clone();
#[cfg(feature = "ip_proxy")]
let ip_proxy_map = ip_proxy_map.clone();
let client_cipher = client_cipher.clone();
let server_cipher = server_cipher.clone();
@@ -130,6 +127,7 @@ pub fn start(
&igmp_server,
current_device.load(),
&ip_route,
#[cfg(feature = "ip_proxy")]
&ip_proxy_map,
&client_cipher,
&server_cipher,
@@ -190,7 +188,7 @@ fn start_simple(
igmp_server: Option<IgmpServer>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
ip_route: Option<ExternalRoute>,
ip_proxy_map: Option<IpProxyMap>,
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
) -> io::Result<()> {
@@ -211,6 +209,7 @@ fn start_simple(
&igmp_server,
current_device.load(),
&ip_route,
#[cfg(feature = "ip_proxy")]
&ip_proxy_map,
&client_cipher,
&server_cipher,
+16 -26
View File
@@ -3,7 +3,6 @@ use std::net::Ipv4Addr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use dashmap::DashMap;
use parking_lot::RwLock;
use packet::igmp::igmp_v2::IgmpV2Packet;
@@ -11,7 +10,6 @@ use packet::igmp::igmp_v3::{IgmpV3QueryPacket, IgmpV3RecordType, IgmpV3ReportPac
use packet::igmp::IgmpType;
use packet::ip::ipv4::protocol::Protocol;
use crate::ip_proxy::DashMapNew;
use crate::tun_tap_device::DeviceWriter;
//1. 定时发送query,启动时20秒一次,连发3次,之后8分钟一次
@@ -51,12 +49,13 @@ impl Multicast {
#[derive(Clone)]
pub struct IgmpServer {
multicast: Arc<DashMap<Ipv4Addr, Arc<RwLock<Multicast>>>>,
multicast: Arc<RwLock<HashMap<Ipv4Addr, Arc<RwLock<Multicast>>>>>,
}
impl IgmpServer {
pub fn new(device_writer: DeviceWriter) -> Self {
let multicast: Arc<DashMap<Ipv4Addr, Arc<RwLock<Multicast>>>> = Arc::new(DashMap::new0());
let multicast: Arc<RwLock<HashMap<Ipv4Addr, Arc<RwLock<Multicast>>>>> =
Arc::new(RwLock::new(HashMap::with_capacity(16)));
std::thread::spawn(move || {
//预留以太网帧头和ip头
let mut buf = [0; 14 + 24 + 12];
@@ -97,16 +96,13 @@ impl IgmpServer {
Self { multicast }
}
pub fn load(&self, multicast_addr: &Ipv4Addr) -> Option<Arc<RwLock<Multicast>>> {
if let Some(entry) = self.multicast.get(multicast_addr) {
Some(entry.value().clone())
} else {
None
}
self.multicast.read().get(multicast_addr).cloned()
}
pub fn handle(&self, buf: &[u8], source: Ipv4Addr) -> crate::Result<()> {
for x in self.multicast.iter() {
let multicast = self.multicast.read();
for (_, v) in multicast.iter() {
let mut list = Vec::new();
let mut write_guard = x.value().write();
let mut write_guard = v.write();
for (ip, time) in &write_guard.members {
if time.elapsed() > Duration::from_secs(30) {
list.push(*ip);
@@ -126,13 +122,7 @@ impl IgmpServer {
if !multicast_addr.is_multicast() {
return Ok(());
}
let multi = {
self.multicast
.entry(multicast_addr)
.or_insert_with(|| Arc::new(RwLock::new(Multicast::new())))
.value()
.clone()
};
let multi = self.add_multicast(multicast_addr);
let mut guard = multi.write();
guard.members.insert(source, Instant::now());
}
@@ -143,8 +133,8 @@ impl IgmpServer {
if !multicast_addr.is_multicast() {
return Ok(());
}
if let Some(entry) = self.multicast.get(&multicast_addr) {
let mut guard = entry.value().write();
if let Some(entry) = self.load(&multicast_addr) {
let mut guard = entry.write();
guard.map.remove(&source);
guard.members.remove(&source);
}
@@ -157,12 +147,7 @@ impl IgmpServer {
if !multicast_addr.is_multicast() {
return Ok(());
}
let multi = self
.multicast
.entry(multicast_addr)
.or_insert_with(|| Arc::new(RwLock::new(Multicast::new())))
.value()
.clone();
let multi = self.add_multicast(multicast_addr);
let mut guard = multi.write();
match group_record.record_type() {
@@ -240,4 +225,9 @@ impl IgmpServer {
}
Ok(())
}
fn add_multicast(&self, multicast_addr: Ipv4Addr) -> Arc<RwLock<Multicast>> {
let value = Arc::new(RwLock::new(Multicast::new()));
self.multicast.write().insert(multicast_addr, value.clone());
value
}
}
+58 -56
View File
@@ -1,20 +1,20 @@
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use std::io;
use std::mem::MaybeUninit;
use std::net::{IpAddr, Ipv4Addr, SocketAddrV4};
use std::sync::Arc;
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use socket2::{Domain, SockAddr, Socket, Type};
use packet::icmp::icmp;
use packet::icmp::icmp::HeaderOther;
use packet::ip::ipv4::packet::IpV4Packet;
use crate::channel::sender::ChannelSender;
use crate::cipher::Cipher;
use crate::handle::CurrentDeviceInfo;
use crate::protocol::body::ENCRYPTION_RESERVED;
use crate::protocol::{NetPacket, Protocol, Version, MAX_TTL};
use packet::icmp::icmp;
use packet::icmp::icmp::HeaderOther;
use packet::ip::ipv4;
use crate::ip_proxy::{send, ProxyHandler};
pub struct IcmpProxy {
icmp_socket: Arc<Socket>,
@@ -47,19 +47,19 @@ impl IcmpProxy {
client_cipher,
})
}
pub fn icmp_socket(&self) -> Arc<Socket> {
self.icmp_socket.clone()
pub fn icmp_handler(&self) -> IcmpHandler {
IcmpHandler(self.icmp_socket.clone(), self.icmp_proxy_map.clone())
}
pub fn start(self) {
let mut buf = [0 as u8; 1500];
let data: &mut [MaybeUninit<u8>] = unsafe { std::mem::transmute(&mut buf[..]) };
let mut buf = [0u8; 4096];
let data: &mut [MaybeUninit<u8>] = unsafe { std::mem::transmute(&mut buf[12..]) };
loop {
match self.recv(data) {
Ok((len, peer_ip)) => {
match peer_ip {
IpAddr::V4(peer_ip) => {
match ipv4::packet::IpV4Packet::new(&mut buf[..len]) {
match IpV4Packet::new(&mut buf[12..12 + len]) {
Ok(mut ipv4_packet) => {
match icmp::IcmpPacket::new(ipv4_packet.payload()) {
Ok(icmp_packet) => {
@@ -73,47 +73,14 @@ impl IcmpProxy {
drop(entry);
ipv4_packet.set_destination_ip(dest_ip);
ipv4_packet.update_checksum();
let current_device =
self.current_device.load();
let virtual_ip =
current_device.virtual_ip();
let connect_server =
current_device.connect_server;
let mut net_packet =
NetPacket::new_encrypt(vec![
0u8;
12 + len + ENCRYPTION_RESERVED
])
.unwrap();
net_packet.set_version(Version::V1);
net_packet.set_protocol(Protocol::IpTurn);
net_packet.set_transport_protocol(crate::protocol::ip_turn_packet::Protocol::Ipv4.into());
net_packet.first_set_ttl(MAX_TTL);
net_packet.set_source(virtual_ip);
net_packet.set_destination(dest_ip);
net_packet
.set_payload(ipv4_packet.buffer)
.unwrap();
if let Err(e) = self
.client_cipher
.encrypt_ipv4(&mut net_packet)
{
log::warn!("加密失败:{}", e);
continue;
}
if self
.sender
.try_send_by_id(
net_packet.buffer(),
&dest_ip,
)
.is_err()
{
let _ = self.sender.send_main(
net_packet.buffer(),
connect_server,
);
}
send(
&mut buf,
len,
dest_ip,
&self.sender,
&self.current_device,
&self.client_cipher,
);
}
}
_ => {
@@ -144,7 +111,42 @@ impl IcmpProxy {
};
Ok((size, addr))
}
// fn send_to(&self, buf: &[u8], addr: SocketAddrV4) -> io::Result<usize> {
// self.icmp_socket.send_to(buf, &SockAddr::from(addr))
// }
}
/// icmp用Identifier来区分,没有Identifier的一律不转发
#[derive(Clone)]
pub struct IcmpHandler(Arc<Socket>, Arc<DashMap<(Ipv4Addr, u16, u16), Ipv4Addr>>);
impl ProxyHandler for IcmpHandler {
fn recv_handle(
&self,
ipv4: &mut IpV4Packet<&mut [u8]>,
source: Ipv4Addr,
destination: Ipv4Addr,
) -> io::Result<bool> {
let dest_ip = ipv4.destination_ip();
//转发到代理目标地址
let icmp_packet = icmp::IcmpPacket::new(ipv4.payload())?;
match icmp_packet.header_other() {
HeaderOther::Identifier(id, seq) => {
self.1.insert((dest_ip, id, seq), source);
self.0.send_to(
ipv4.payload(),
&SockAddr::from(SocketAddrV4::new(dest_ip, 0)),
)?;
}
_ => {
log::warn!(
"不支持的ip代理Icmp协议:{}->{}->{}",
source,
destination,
dest_ip
);
}
}
Ok(true)
}
fn send_handle(&self, _ipv4: &mut IpV4Packet<&mut [u8]>) -> io::Result<()> {
Ok(())
}
}
+142 -49
View File
@@ -1,14 +1,24 @@
use crate::ip_proxy::tcp_proxy::TcpProxy;
use crate::ip_proxy::udp_proxy::UdpProxy;
use dashmap::DashMap;
#[cfg(not(target_os = "android"))]
use socket2::{SockAddr, Socket};
#[cfg(not(target_os = "android"))]
use std::net::Ipv4Addr;
use std::net::SocketAddrV4;
use std::sync::Arc;
use std::{io, thread};
use tokio::net::{TcpListener, UdpSocket};
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use packet::ip::ipv4;
use tokio::net::UdpSocket;
use packet::ip::ipv4::packet::IpV4Packet;
use crate::channel::sender::ChannelSender;
use crate::cipher::Cipher;
use crate::handle::CurrentDeviceInfo;
#[cfg(not(target_os = "android"))]
use crate::ip_proxy::icmp_proxy::IcmpHandler;
use crate::ip_proxy::tcp_proxy::{TcpHandler, TcpProxy};
use crate::ip_proxy::udp_proxy::{UdpHandler, UdpProxy};
use crate::protocol;
use crate::protocol::{NetPacket, Version, MAX_TTL};
#[cfg(not(target_os = "android"))]
pub mod icmp_proxy;
@@ -20,6 +30,16 @@ pub trait DashMapNew {
fn new_cap(capacity: usize) -> Self;
}
pub trait ProxyHandler {
fn recv_handle(
&self,
ipv4: &mut IpV4Packet<&mut [u8]>,
source: Ipv4Addr,
destination: Ipv4Addr,
) -> io::Result<bool>;
fn send_handle(&self, ipv4: &mut IpV4Packet<&mut [u8]>) -> io::Result<()>;
}
impl<'a, K: 'a + Eq + std::hash::Hash, V: 'a> DashMapNew for DashMap<K, V> {
fn new0() -> Self {
Self::new_cap(0)
@@ -52,72 +72,145 @@ pub enum Protocol {
#[derive(Clone)]
pub struct IpProxyMap {
pub(crate) tcp_proxy_port: u16,
pub(crate) udp_proxy_port: u16,
//真实源地址 -> 目的地址
pub(crate) tcp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>>,
pub(crate) udp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>>,
// icmp用Identifier来区分,没有Identifier的一律不转发
#[cfg(not(target_os = "android"))]
pub(crate) icmp_proxy_map: Arc<DashMap<(Ipv4Addr, u16, u16), Ipv4Addr>>,
#[cfg(not(target_os = "android"))]
icmp_socket: Arc<Socket>,
}
impl IpProxyMap {
#[cfg(not(target_os = "android"))]
pub fn send_icmp(&self, buf: &[u8], dest: &Ipv4Addr) -> io::Result<usize> {
self.icmp_socket
.send_to(buf, &SockAddr::from(SocketAddrV4::new(*dest, 0)))
}
pub(crate) icmp_handler: IcmpHandler,
pub(crate) tcp_handler: TcpHandler,
pub(crate) udp_handler: UdpHandler,
}
#[cfg(not(target_os = "android"))]
pub async fn init_proxy(
#[cfg(not(target_os = "android"))] sender: crate::channel::sender::ChannelSender,
#[cfg(not(target_os = "android"))] current_device: Arc<
crossbeam_utils::atomic::AtomicCell<crate::handle::CurrentDeviceInfo>,
>,
#[cfg(not(target_os = "android"))] client_cipher: crate::cipher::Cipher,
sender: ChannelSender,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
client_cipher: Cipher,
) -> io::Result<(TcpProxy, UdpProxy, IpProxyMap)> {
let tcp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>> = Arc::new(DashMap::new0());
let udp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>> = Arc::new(DashMap::new0());
#[cfg(not(target_os = "android"))]
let icmp_proxy_map: Arc<DashMap<(Ipv4Addr, u16, u16), Ipv4Addr>> = Arc::new(DashMap::new0());
let tcp_listener = TcpListener::bind("0.0.0.0:0").await?;
let udp_socket = UdpSocket::bind("0.0.0.0:0").await?;
let tcp_proxy_port = tcp_listener.local_addr()?.port();
let udp_proxy_port = udp_socket.local_addr()?.port();
let tcp_proxy = TcpProxy::new(tcp_listener, tcp_proxy_map.clone());
let udp_proxy = UdpProxy::new(udp_socket, udp_proxy_map.clone());
#[cfg(not(target_os = "android"))]
let icmp_socket = {
let addr = SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0);
let addr = SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0);
let tcp_proxy = TcpProxy::new(addr, tcp_proxy_map.clone()).await?;
let tcp_handler = tcp_proxy.tcp_handler();
let udp_proxy = UdpProxy::new(udp_socket, udp_proxy_map.clone())?;
let udp_handler = udp_proxy.udp_handler();
let icmp_handler = {
let icmp_proxy = icmp_proxy::IcmpProxy::new(
addr,
icmp_proxy_map.clone(),
sender.clone(),
current_device.clone(),
client_cipher,
client_cipher.clone(),
)?;
let icmp_socket = icmp_proxy.icmp_socket();
let icmp_handler = icmp_proxy.icmp_handler();
thread::spawn(move || {
icmp_proxy.start();
});
icmp_socket
icmp_handler
};
Ok((
tcp_proxy,
udp_proxy,
IpProxyMap {
tcp_proxy_port,
udp_proxy_port,
tcp_proxy_map,
udp_proxy_map,
#[cfg(not(target_os = "android"))]
icmp_proxy_map,
#[cfg(not(target_os = "android"))]
icmp_socket,
tcp_handler,
udp_handler,
icmp_handler,
},
))
}
#[cfg(target_os = "android")]
pub async fn init_proxy() -> io::Result<(TcpProxy, UdpProxy, IpProxyMap)> {
let tcp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>> = Arc::new(DashMap::new0());
let udp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>> = Arc::new(DashMap::new0());
let addr = SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0);
let udp_socket = UdpSocket::bind("0.0.0.0:0").await?;
let tcp_proxy = TcpProxy::new(addr, tcp_proxy_map.clone()).await?;
let tcp_handler = tcp_proxy.tcp_handler();
let udp_proxy = UdpProxy::new(udp_socket, udp_proxy_map.clone())?;
let udp_handler = udp_proxy.udp_handler();
Ok((
tcp_proxy,
udp_proxy,
IpProxyMap {
tcp_handler,
udp_handler,
},
))
}
pub fn send(
buf: &mut [u8],
data_len: usize,
dest_ip: Ipv4Addr,
sender: &ChannelSender,
current_device: &AtomicCell<CurrentDeviceInfo>,
client_cipher: &Cipher,
) {
let current_device = current_device.load();
let virtual_ip = current_device.virtual_ip();
let mut net_packet = NetPacket::new0(12 + data_len, buf).unwrap();
net_packet.set_version(Version::V1);
net_packet.set_protocol(protocol::Protocol::IpTurn);
net_packet.set_transport_protocol(protocol::ip_turn_packet::Protocol::Ipv4.into());
net_packet.first_set_ttl(MAX_TTL);
net_packet.set_source(virtual_ip);
net_packet.set_destination(dest_ip);
if let Err(e) = client_cipher.encrypt_ipv4(&mut net_packet) {
log::warn!("加密失败:{}", e);
return;
}
if sender
.try_send_by_id(net_packet.buffer(), &dest_ip)
.is_err()
{
let connect_server = current_device.connect_server;
if let Err(e) = sender.send_main(net_packet.buffer(), connect_server) {
log::warn!("发送到目标失败:{},{}", e, connect_server);
}
}
}
impl ProxyHandler for IpProxyMap {
fn recv_handle(
&self,
ipv4: &mut IpV4Packet<&mut [u8]>,
source: Ipv4Addr,
destination: Ipv4Addr,
) -> io::Result<bool> {
match ipv4.protocol() {
ipv4::protocol::Protocol::Tcp => {
self.tcp_handler.recv_handle(ipv4, source, destination)
}
ipv4::protocol::Protocol::Udp => {
self.udp_handler.recv_handle(ipv4, source, destination)
}
#[cfg(not(target_os = "android"))]
ipv4::protocol::Protocol::Icmp => {
self.icmp_handler.recv_handle(ipv4, source, destination)
}
_ => {
log::warn!(
"不支持的ip代理ipv4协议{:?}:{}->{}->{}",
ipv4.protocol(),
source,
destination,
ipv4.destination_ip()
);
Ok(false)
}
}
}
fn send_handle(&self, ipv4: &mut IpV4Packet<&mut [u8]>) -> io::Result<()> {
match ipv4.protocol() {
ipv4::protocol::Protocol::Tcp => self.tcp_handler.send_handle(ipv4),
ipv4::protocol::Protocol::Udp => self.udp_handler.send_handle(ipv4),
_ => Ok(()),
}
}
}
+61 -6
View File
@@ -1,7 +1,10 @@
use crate::ip_proxy::ProxyHandler;
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use packet::ip::ipv4::packet::IpV4Packet;
use packet::tcp::tcp::TcpPacket;
use std::io;
use std::net::{SocketAddr, SocketAddrV4};
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::io::AsyncReadExt;
@@ -10,19 +13,26 @@ use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
use tokio::net::{TcpListener, TcpStream};
pub struct TcpProxy {
tcp_proxy_port: u16,
tcp_listener: TcpListener,
//真实源地址 -> 目的地址
tcp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>>,
}
impl TcpProxy {
pub fn new(
tcp_listener: TcpListener,
pub async fn new(
addr: SocketAddrV4,
tcp_proxy_map: Arc<DashMap<SocketAddrV4, SocketAddrV4>>,
) -> Self {
Self {
) -> io::Result<Self> {
let tcp_listener = TcpListener::bind(addr).await?;
Ok(Self {
tcp_proxy_port: tcp_listener.local_addr()?.port(),
tcp_listener,
tcp_proxy_map,
}
})
}
pub fn tcp_handler(&self) -> TcpHandler {
TcpHandler(self.tcp_proxy_port, self.tcp_proxy_map.clone())
}
pub async fn start(self) {
let tcp_listener = self.tcp_listener;
@@ -121,3 +131,48 @@ async fn copy(
}
Ok(())
}
#[derive(Clone)]
pub struct TcpHandler(u16, Arc<DashMap<SocketAddrV4, SocketAddrV4>>);
impl ProxyHandler for TcpHandler {
fn recv_handle(
&self,
ipv4: &mut IpV4Packet<&mut [u8]>,
source: Ipv4Addr,
destination: Ipv4Addr,
) -> io::Result<bool> {
let dest_ip = ipv4.destination_ip();
//转发到代理目标地址
let mut tcp_packet = TcpPacket::new(source, destination, ipv4.payload_mut())?;
let source_port = tcp_packet.source_port();
let dest_port = tcp_packet.destination_port();
tcp_packet.set_destination_port(self.0);
tcp_packet.update_checksum();
ipv4.set_destination_ip(destination);
ipv4.update_checksum();
let key = SocketAddrV4::new(source, source_port);
//https://github.com/crossbeam-rs/crossbeam/issues/1023
self.1.insert(key, SocketAddrV4::new(dest_ip, dest_port));
Ok(false)
}
fn send_handle(&self, ipv4: &mut IpV4Packet<&mut [u8]>) -> io::Result<()> {
let src_ip = ipv4.source_ip();
let dest_ip = ipv4.destination_ip();
let dest_addr = {
let tcp_packet = TcpPacket::new(src_ip, dest_ip, ipv4.payload_mut())?;
SocketAddrV4::new(dest_ip, tcp_packet.destination_port())
};
if let Some(entry) = self.1.get(&dest_addr) {
let source_addr = entry.value();
let source_ip = *source_addr.ip();
let mut tcp_packet = TcpPacket::new(source_ip, dest_ip, ipv4.payload_mut())?;
tcp_packet.set_source_port(source_addr.port());
tcp_packet.update_checksum();
ipv4.set_source_ip(source_ip);
ipv4.update_checksum();
}
Ok(())
}
}
+62 -4
View File
@@ -1,8 +1,10 @@
use crate::ip_proxy::DashMapNew;
use crate::ip_proxy::{DashMapNew, ProxyHandler};
use crossbeam_utils::atomic::AtomicCell;
use dashmap::DashMap;
use packet::ip::ipv4::packet::IpV4Packet;
use packet::udp::udp::UdpPacket;
use std::io;
use std::net::{SocketAddr, SocketAddrV4};
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::sync::Arc;
use std::time::Duration;
use tokio::net::UdpSocket;
@@ -10,14 +12,26 @@ use tokio::time::Instant;
/// 一个udp代理,作用是利用系统协议栈,将udp数据报解析出来再转发到目的地址
pub struct UdpProxy {
udp_proxy_port: u16,
udp_socket: Arc<UdpSocket>,
map: Arc<DashMap<SocketAddrV4, SocketAddrV4>>,
}
impl UdpProxy {
pub fn new(udp_socket: UdpSocket, map: Arc<DashMap<SocketAddrV4, SocketAddrV4>>) -> Self {
pub fn new(
udp_socket: UdpSocket,
map: Arc<DashMap<SocketAddrV4, SocketAddrV4>>,
) -> io::Result<Self> {
let udp_socket = Arc::new(udp_socket);
Self { udp_socket, map }
let udp_proxy_port = udp_socket.local_addr()?.port();
Ok(Self {
udp_proxy_port,
udp_socket,
map,
})
}
pub fn udp_handler(&self) -> UdpHandler {
UdpHandler(self.udp_proxy_port, self.map.clone())
}
pub async fn start(self) {
let map = self.map;
@@ -122,3 +136,47 @@ async fn start0(
}
Ok(())
}
#[derive(Clone)]
pub struct UdpHandler(u16, Arc<DashMap<SocketAddrV4, SocketAddrV4>>);
impl ProxyHandler for UdpHandler {
fn recv_handle(
&self,
ipv4: &mut IpV4Packet<&mut [u8]>,
source: Ipv4Addr,
destination: Ipv4Addr,
) -> io::Result<bool> {
let dest_ip = ipv4.destination_ip();
//转发到代理目标地址
let mut udp_packet = UdpPacket::new(source, destination, ipv4.payload_mut())?;
let source_port = udp_packet.source_port();
let dest_port = udp_packet.destination_port();
udp_packet.set_destination_port(self.0);
udp_packet.update_checksum();
ipv4.set_destination_ip(destination);
ipv4.update_checksum();
let key = SocketAddrV4::new(source, source_port);
self.1.insert(key, SocketAddrV4::new(dest_ip, dest_port));
Ok(false)
}
fn send_handle(&self, ipv4: &mut IpV4Packet<&mut [u8]>) -> io::Result<()> {
let src_ip = ipv4.source_ip();
let dest_ip = ipv4.destination_ip();
let dest_addr = {
let udp_packet = UdpPacket::new(src_ip, dest_ip, ipv4.payload_mut())?;
SocketAddrV4::new(dest_ip, udp_packet.destination_port())
};
if let Some(entry) = self.1.get(&dest_addr) {
let source_addr = entry.value();
let source_ip = *source_addr.ip();
let mut udp_packet = UdpPacket::new(source_ip, dest_ip, ipv4.payload_mut())?;
udp_packet.set_source_port(source_addr.port());
udp_packet.update_checksum();
ipv4.set_source_ip(source_ip);
ipv4.update_checksum();
}
Ok(())
}
}
+2 -1
View File
@@ -1,5 +1,5 @@
use crate::error::Error;
pub const VNT_VERSION: &'static str = "1.2.5";
pub const VNT_VERSION: &'static str = "1.2.8";
pub type Result<T> = std::result::Result<T, Error>;
pub mod channel;
@@ -9,6 +9,7 @@ pub mod error;
pub mod external_route;
pub mod handle;
pub mod igmp_server;
#[cfg(feature = "ip_proxy")]
pub mod ip_proxy;
pub mod nat;
pub mod proto;
+8 -5
View File
@@ -7,12 +7,12 @@ edition = "2021"
[dependencies]
log = "0.4.17"
winreg = "0.7"
winreg = "0.51.0"
scopeguard = "1.1"
libloading = "0.7"
widestring = "0.4"
libloading = "0.8.0"
widestring = "1.0.2"
once_cell = "1.8"
itertools = "0.10.1"
itertools = "0.11.0"
rand = "0.8.5"
[dependencies.winapi]
version = "0.3"
@@ -30,5 +30,8 @@ features = [
"ipexport",
"iphlpapi",
"handleapi",
"ifdef"
"ifdef",
"minwinbase",
"basetsd",
"impl-default"
]
+5 -5
View File
@@ -119,14 +119,14 @@ pub fn create_interface() -> io::Result<NET_LUID> {
KEY_QUERY_VALUE | KEY_NOTIFY,
)?;
let key = RegKey::predef(key);
let key = RegKey::predef(key as _);
while let Err(_) = key.get_value::<DWORD, &str>("*IfType") {
ffi::notify_change_key_value(key.raw_handle(), TRUE, REG_NOTIFY_CHANGE_NAME, 2000)?;
ffi::notify_change_key_value(key.raw_handle() as _, TRUE, REG_NOTIFY_CHANGE_NAME, 2000)?;
}
while let Err(_) = key.get_value::<DWORD, &str>("NetLuidIndex") {
ffi::notify_change_key_value(key.raw_handle(), TRUE, REG_NOTIFY_CHANGE_NAME, 2000)?;
ffi::notify_change_key_value(key.raw_handle() as _, TRUE, REG_NOTIFY_CHANGE_NAME, 2000)?;
}
let if_type: DWORD = key.get_value("*IfType")?;
@@ -179,7 +179,7 @@ pub fn check_interface(luid: &NET_LUID) -> io::Result<()> {
DIREG_DRV,
KEY_QUERY_VALUE | KEY_NOTIFY,
) {
Ok(key) => RegKey::predef(key),
Ok(key) => RegKey::predef(key as _),
Err(_) => continue,
};
@@ -248,7 +248,7 @@ pub fn delete_interface(luid: &NET_LUID) -> io::Result<()> {
DIREG_DRV,
KEY_QUERY_VALUE | KEY_NOTIFY,
) {
Ok(key) => RegKey::predef(key),
Ok(key) => RegKey::predef(key as _),
Err(_) => continue,
};