Compare commits

...
96 Commits
Author SHA1 Message Date
vnt-dev 501a9e8198 Merge pull request #99 from vnt-dev/1.2.x
1.2.x
2024-10-20 14:13:57 +08:00
lubeilin 8aa4736b01 Merge remote-tracking branch 'vnt-release/1.2.x' into 1.2.x- 2024-10-14 16:53:45 +08:00
lubeilin d5e10a8210 调整数据读取 2024-10-14 16:53:35 +08:00
lbl 1165ee52c7 v3 2024-10-13 12:36:37 +08:00
lbl 8a66bbe1af version=1.2.14 2024-10-13 12:12:41 +08:00
lbl c91d8a2734 log 2024-10-13 12:11:16 +08:00
lbl 09a315a0f1 绑定本地网卡名称 2024-10-13 12:09:30 +08:00
vnt-dev 2979f2ef6f Merge pull request #97 from vnt-dev/vnt-dev-patch-1
Update README.md
2024-10-03 15:49:38 +08:00
vnt-dev 8225cb7877 Update README.md 2024-10-03 15:49:18 +08:00
vnt-dev 129ca1ec85 Merge pull request #86 from vnt-dev/1.2.x
1.2.x
2024-08-21 17:00:34 +08:00
lbl8603 96b67c6162 更新文档 2024-08-12 22:04:31 +08:00
lbl8603 ce02b30b2b 去除默认绑定网卡的逻辑 2024-08-12 22:04:17 +08:00
lbl8603 2fbdfe920e 增加绑定网卡 2024-08-08 22:02:46 +08:00
lbl8603 7901407d69 解决已知问题 2024-08-08 21:30:19 +08:00
lbl8603 e6cfdec9c6 调整默认网卡的逻辑 2024-08-08 20:38:58 +08:00
lbl8603 7e0de2c4e6 忽略绑定失败的错误 2024-08-07 23:14:13 +08:00
lbl8603 803af55246 增加日志 2024-08-07 22:34:48 +08:00
lbl8603 8e1a8fa7f0 增加feature判断 2024-08-07 21:48:58 +08:00
lbl8603 fc6bf407c4 wintun.dll校验失败则返回提示 2024-08-07 21:32:19 +08:00
lbl8603 dc4e472f20 提示虚拟网卡创建失败的信息 2024-08-07 21:29:55 +08:00
lbl8603 afff49e61a set_reuse_port 2024-08-06 22:03:18 +08:00
lbl8603 0f9ac2ac87 NAT1下的tcp打洞 2024-08-05 20:44:54 +08:00
vnt-dev cce23b9661 Merge pull request #67 from vnt-dev/1.2.x
1.2.x
2024-08-04 16:29:29 +08:00
lbl8603 4347ed68c3 Merge branch 'refs/heads/bugfix/2024-08-01-修复打洞问题' into 1.2.x 2024-08-01 23:24:10 +08:00
lbl8603 64d68c8a84 修复打洞问题 2024-08-01 23:23:23 +08:00
lbl8603 210b7c959e 调整日志 2024-08-01 21:56:09 +08:00
lbl8603 e8322adbcc 修复重启后不打洞的问题 2024-08-01 21:26:31 +08:00
lbl8603 e523b02b58 android增加wg选项 2024-07-31 21:37:19 +08:00
lbl8603 13df028cd9 更新版本号 2024-07-31 11:01:31 +08:00
lbl8603 4550bea063 更新版本 2024-07-31 11:00:20 +08:00
lbl8603 be8d4cbb8b fmt 2024-07-31 10:00:28 +08:00
lbl8603 ace0268a8c Merge branch 'refs/heads/1.2.x' into features/2024-07-30-分离协议栈
# Conflicts:
#	vnt/src/channel/punch.rs
2024-07-31 09:57:55 +08:00
lbl8603 56fd0d7a4f v4 socket绑定网卡 2024-07-30 23:37:54 +08:00
lbl8603 91ee751b07 Merge branch 'refs/heads/bugfix-2024-07-30-issues#65' into 1.2.x 2024-07-30 22:54:37 +08:00
lbl8603 fa9903ace1 修复配置文件没有读取加密方式的问题 2024-07-30 22:54:17 +08:00
lbl8603 c2854352df Merge branch 'refs/heads/features/2024-07-30-调整文档' into 1.2.x 2024-07-30 22:52:26 +08:00
lbl8603 b3472fb5b3 调整说明 2024-07-30 22:52:04 +08:00
lbl8603 e373c9ee16 支持选择tcp或udp打洞 2024-07-25 20:54:08 +08:00
vnt-dev 13b7b1761d Merge pull request #63 from vnt-dev/1.2.x
1.2.x
2024-07-25 10:28:28 +08:00
lbl8603 352f322f61 生成guid 2024-07-24 22:11:50 +08:00
lbl8603 be966c4f83 简化广播 2024-07-23 22:25:55 +08:00
lbl8603 b8cbf2cdac 不在线的可以不转发 2024-07-20 23:26:11 +08:00
lbl8603 05cf0e1a6f 修改版本 2024-07-20 14:48:56 +08:00
lbl8603 f90ef96a5d 增加sys-locale 2024-07-20 11:12:45 +08:00
lbl8603 81c6c8c1fc Merge branch 'refs/heads/1.2.x' into 1.2.x-2024-07-20-1
# Conflicts:
#	common/src/cli.rs
2024-07-20 11:10:15 +08:00
lbl8603 7ebdffcdd3 支持wg 2024-07-20 10:38:18 +08:00
lbl8603 1abe33cb16 Merge pull request #61 from jslyrd/main
添加英文帮助信息
2024-07-16 23:11:44 +08:00
jslyrd 965cbfbb7e 添加英文帮助信息 2024-07-16 22:32:48 +08:00
lbl8603 aa332b4f4d Merge pull request #60 from lbl8603/1.2.x
1.2.x
2024-07-13 15:53:53 +08:00
lbl8603 14ee9c4632 Merge branch 'refs/heads/1.2.x' into 1.2.x-2024-07-04 2024-07-13 12:11:24 +08:00
lbl8603 ddfa89167d 修改地址探测和转发路径 2024-07-13 12:09:15 +08:00
lbl8603 1f9ed7b314 修改features 2024-07-13 12:01:41 +08:00
lbl8603 dc45602661 Merge pull request #58 from lbl8603/1.2.x
调整添加转发路径的逻辑
2024-07-10 23:09:49 +08:00
lbl8603 27c0f389ee 调整添加转发路径的逻辑 2024-07-10 22:54:13 +08:00
lbl8603 59d6bfd957 Merge pull request #56 from lbl8603/1.2.x
1.2.x
2024-07-07 23:29:16 +08:00
lbl8603 31b8661b7d 设置证书 2024-07-07 22:38:01 +08:00
lbl8603 8ae20497c6 避免除0 2024-07-07 13:05:31 +08:00
lbl8603 a70b4f30b5 增加统计模块 2024-07-06 17:18:44 +08:00
lbl8603 df4795c9c4 加入少量轮询 2024-07-06 17:13:32 +08:00
lbl8603 c21a73f950 忽略初次错误 2024-07-06 16:45:55 +08:00
lbl8603 29cd111a49 fmt 2024-07-06 16:44:30 +08:00
lbl8603 367a56d346 Merge branch 'refs/heads/1.2.x' into 1.2.x-2024-07-04 2024-07-06 16:28:14 +08:00
lbl8603 d81ac6368e 增加流量统计 2024-07-06 16:27:08 +08:00
lbl8603 a228b62d23 Merge pull request #55 from Iron-Yang-Go/1.2.x
Try to execute 'dmidecode' command to get the system identifier first
2024-07-03 22:58:24 +08:00
Iron-Yang 995ff9b059 Try to execute 'dmidecode' command to get the system identifier first 2024-07-03 22:46:59 +08:00
lbl8603 7dc78cc170 修复时间相差导致的异常 2024-07-03 22:34:29 +08:00
lbl8603 7e218355f2 编译websocket 2024-07-02 21:18:08 +08:00
lbl8603 98c394c993 修改错误输出 2024-07-02 21:17:08 +08:00
lbl8603 31b06cd713 去除缓冲区设置 2024-07-01 23:04:08 +08:00
lbl8603 d7266926d8 增加Sync 2024-07-01 23:03:52 +08:00
lbl8603 1df5a1cfb1 去除不安全的计数器 2024-06-30 23:02:50 +08:00
lbl8603 8658bd3601 去除println 2024-06-30 22:19:05 +08:00
lbl8603 17d1ad3716 支持websocket协议 2024-06-30 22:16:30 +08:00
lbl8603 728598ba8e 处理遗留问题 2024-06-29 18:44:36 +08:00
lbl8603 218483f431 支持upnp 2024-06-29 17:29:37 +08:00
lbl8603 1f80e06d9d 服务端流量过滤 2024-06-29 17:28:30 +08:00
lbl8603 5e56064ec6 ipv6转ipv4判断 2024-06-29 17:26:52 +08:00
lbl8603 31f0213fc5 优化停止逻辑 2024-06-27 22:09:25 +08:00
lbl8603 54b1fef164 增加日志 2024-06-27 22:09:13 +08:00
lbl8603 7c18df0a6f 参考std判断公网IP 2024-06-27 21:59:57 +08:00
lbl8603 916fd8254b 修改stun 2024-06-27 21:58:17 +08:00
lbl8603 9e249862dc 排除虚拟网段 2024-06-26 21:53:59 +08:00
lbl8603 3773c09f57 调整任务停止逻辑 2024-06-25 22:48:06 +08:00
lbl8603 6798c652f9 减少socket数目,降低网络压力 2024-06-25 22:47:38 +08:00
lbl8603 382d5b61ba 调整退避速度 2024-06-25 22:47:19 +08:00
lbl8603 ac162eba66 调整打洞频率 2024-06-20 22:22:01 +08:00
lbl8603 05a60b3cb7 增加包长度上限 2024-06-17 23:46:34 +08:00
lbl8603 7f210e9319 调整获取地址频率 2024-06-17 23:44:11 +08:00
lbl8603 481c00629a 更新地址成功则返回true 2024-06-17 23:43:54 +08:00
lbl8603 bf55ec9512 修改文件名 2024-06-17 22:41:08 +08:00
lbl8603 e36e45054c Merge pull request #49 from lbl8603/1.2.x
1.2.x
2024-06-01 17:00:51 +08:00
lbl8603 39170b74ca Merge pull request #43 from lbl8603/1.2.x
调整条件编译
2024-05-15 20:32:05 +08:00
lbl8603 0e3f06429b Merge pull request #42 from lbl8603/1.2.x
处理unix去掉所有模块的编译问题
2024-05-14 09:25:52 +08:00
lbl8603 ee7c597bd8 Merge pull request #41 from lbl8603/1.2.x
1.2.x
2024-05-13 22:53:51 +08:00
lbl8603 7f500d72c7 Merge pull request #39 from lbl8603/1.2.x
支持--no-default-features编译
2024-05-11 13:31:04 +08:00
lbl8603 4dca4c4f22 Merge pull request #38 from lbl8603/1.2.x
1.2.x
2024-05-11 09:21:57 +08:00
81 changed files with 3906 additions and 1819 deletions
+16 -16
View File
@@ -44,40 +44,40 @@ jobs:
FEATURES: default
- TARGET: x86_64-unknown-linux-musl # test in an alpine container on a mac
OS: ubuntu-latest
FEATURES: ring-cipher,openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: aarch64-unknown-linux-musl # tested on aws t4g.nano in alpine container
OS: ubuntu-latest
FEATURES: ring-cipher,openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: armv7-unknown-linux-musleabihf # raspberry pi 2-3-4, not tested
OS: ubuntu-latest
FEATURES: openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: armv7-unknown-linux-musleabi # raspberry pi 2-3-4, not tested
OS: ubuntu-latest
FEATURES: openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: arm-unknown-linux-musleabihf # raspberry pi 0-1, not tested
OS: ubuntu-latest
FEATURES: ring-cipher,openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: arm-unknown-linux-musleabi # raspberry pi 0-1, not tested
OS: ubuntu-latest
FEATURES: ring-cipher,openssl-vendored
FEATURES: ring-cipher,wss
- 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
FEATURES: ring-cipher,wss
- TARGET: aarch64-apple-darwin # tested on a mac, is not properly signed so there are security warnings
OS: macos-latest
FEATURES: ring-cipher,openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: i686-pc-windows-msvc # tested on a windows machine
OS: windows-2019
FEATURES: ring-cipher,openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: x86_64-pc-windows-msvc # tested on a windows machine
OS: windows-latest
FEATURES: ring-cipher,openssl-vendored
FEATURES: ring-cipher,wss
- TARGET: mipsel-unknown-linux-musl # openwrt
OS: ubuntu-latest
FEATURES: openssl-vendored,ring-cipher
FEATURES: ring-cipher,wss
- TARGET: mips-unknown-linux-musl # openwrt
OS: ubuntu-latest
FEATURES: openssl-vendored
FEATURES: ring-cipher,wss
# needs: test
runs-on: ${{ matrix.OS }}
env:
@@ -86,7 +86,7 @@ jobs:
OS: ${{ matrix.OS }}
FEATURES: ${{ matrix.FEATURES }}
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Init submodules
uses: snickerbockers/submodules-init@v4
- name: Cargo cache
@@ -217,11 +217,11 @@ jobs:
fi
mv ./target/$TARGET/release/$EXEC_VNT_CLI ./artifacts/$EXEC_VNT_CLI
mv ./target/$TARGET/release/$EXEC_VN_LINK_CLI ./artifacts/$EXEC_VN_LINK_CLI
mv ./README ./artifacts/README
mv ./README ./artifacts/README.txt
cd ./artifacts
tar -czf vnt-$TARGET-$TAG.tar.gz *
- name: Archive artifact
uses: actions/upload-artifact@v2
uses: actions/upload-artifact@v3
with:
name: vnt-cli
path: |
@@ -233,7 +233,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Download artifacts
uses: actions/download-artifact@v2
uses: actions/download-artifact@v3
with:
name: vnt-cli
path: ./artifacts
+4 -1
View File
@@ -1,3 +1,6 @@
target/*
vnt/src/proto/*
common/src/generated_serial_number.rs
common/src/generated_serial_number.rs
# RustRover
.idea
Generated
+478 -52
View File
@@ -88,6 +88,18 @@ version = "1.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69f7f8c3906b62b754cd5326047894316021dcfe5a194c8ea52bdd94934a3457"
[[package]]
name = "attohttpc"
version = "0.16.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb8867f378f33f78a811a8eb9bf108ad99430d7aad43315dd9319c827ef6247"
dependencies = [
"http 0.2.12",
"log",
"url",
"wildmatch",
]
[[package]]
name = "autocfg"
version = "1.2.0"
@@ -109,6 +121,12 @@ dependencies = [
"rustc-demangle",
]
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.6.0"
@@ -262,7 +280,7 @@ dependencies = [
"js-sys",
"num-traits",
"wasm-bindgen",
"windows-targets 0.52.5",
"windows-targets 0.52.6",
]
[[package]]
@@ -289,7 +307,7 @@ dependencies = [
[[package]]
name = "common"
version = "1.2.10"
version = "1.2.14"
dependencies = [
"anyhow",
"chrono",
@@ -301,6 +319,7 @@ dependencies = [
"rand",
"serde",
"serde_yaml",
"sys-locale",
"uuid",
"vnt",
]
@@ -324,6 +343,16 @@ version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
[[package]]
name = "core-foundation"
version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "core-foundation-sys"
version = "0.8.6"
@@ -415,6 +444,12 @@ dependencies = [
"cipher",
]
[[package]]
name = "data-encoding"
version = "2.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8566979429cf69b49a5c740c60791108e86440e8be149bbea4fe54d2c32d6e2"
[[package]]
name = "der"
version = "0.7.9"
@@ -513,6 +548,59 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-core"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d"
[[package]]
name = "futures-macro"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.60",
]
[[package]]
name = "futures-sink"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5"
[[package]]
name = "futures-task"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004"
[[package]]
name = "futures-util"
version = "0.3.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48"
dependencies = [
"futures-core",
"futures-macro",
"futures-sink",
"futures-task",
"pin-project-lite",
"pin-utils",
"slab",
]
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -604,6 +692,34 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "http"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1"
dependencies = [
"bytes",
"fnv",
"itoa",
]
[[package]]
name = "http"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258"
dependencies = [
"bytes",
"fnv",
"itoa",
]
[[package]]
name = "httparse"
version = "1.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9"
[[package]]
name = "humantime"
version = "2.1.0"
@@ -633,6 +749,29 @@ dependencies = [
"cc",
]
[[package]]
name = "idna"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6"
dependencies = [
"unicode-bidi",
"unicode-normalization",
]
[[package]]
name = "igd"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556b5a75cd4adb7c4ea21c64af1c48cefb2ce7d43dc4352c720a1fe47c21f355"
dependencies = [
"attohttpc",
"log",
"rand",
"url",
"xmltree",
]
[[package]]
name = "indexmap"
version = "1.9.3"
@@ -719,9 +858,9 @@ checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
[[package]]
name = "libc"
version = "0.2.153"
version = "0.2.155"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c"
[[package]]
name = "libloading"
@@ -730,7 +869,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19"
dependencies = [
"cfg-if",
"windows-targets 0.52.5",
"windows-targets 0.52.6",
]
[[package]]
@@ -742,7 +881,7 @@ checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
[[package]]
name = "libsm"
version = "0.5.1"
source = "git+https://github.com/lbl8603/libsm#f9e1b8cf20d0829efb4934a940d0ba4f3ee0ac14"
source = "git+https://github.com/vnt-dev/libsm#f9e1b8cf20d0829efb4934a940d0ba4f3ee0ac14"
dependencies = [
"byteorder",
"getrandom",
@@ -816,7 +955,7 @@ dependencies = [
[[package]]
name = "lwip-rs"
version = "0.1.0"
source = "git+https://github.com/lbl8603/lwip-rs#3133f0c3bde55333a27641182ae3550e7acc2a39"
source = "git+https://github.com/vnt-dev/lwip-rs#3133f0c3bde55333a27641182ae3550e7acc2a39"
dependencies = [
"bindgen",
"cc",
@@ -866,6 +1005,18 @@ dependencies = [
"windows-sys 0.48.0",
]
[[package]]
name = "network-interface"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "433419f898328beca4f2c6c73a1b52540658d92b0a99f0269330457e0fd998d5"
dependencies = [
"cc",
"libc",
"thiserror",
"winapi",
]
[[package]]
name = "nom"
version = "7.1.3"
@@ -965,6 +1116,12 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"
[[package]]
name = "openssl-probe"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-src"
version = "300.1.3+3.1.2"
@@ -976,7 +1133,7 @@ dependencies = [
[[package]]
name = "openssl-sys"
version = "0.9.93"
source = "git+https://github.com/lbl8603/rust-openssl#e8b3d2c02d2d07a0e4a82ff4e4bef210f4bc71c8"
source = "git+https://github.com/vnt-dev/rust-openssl#e8b3d2c02d2d07a0e4a82ff4e4bef210f4bc71c8"
dependencies = [
"cc",
"libc",
@@ -1033,12 +1190,24 @@ dependencies = [
"base64ct",
]
[[package]]
name = "percent-encoding"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e"
[[package]]
name = "pin-project-lite"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "pkcs1"
version = "0.7.5"
@@ -1116,9 +1285,9 @@ dependencies = [
[[package]]
name = "protobuf"
version = "3.4.0"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "58678a64de2fced2bdec6bca052a6716a0efe692d6e3f53d1bda6a1def64cfc0"
checksum = "b55bad9126f378a853655831eb7363b7b01b81d19f8cb1218861086ca4a1a61e"
dependencies = [
"once_cell",
"protobuf-support",
@@ -1127,9 +1296,9 @@ dependencies = [
[[package]]
name = "protobuf-codegen"
version = "3.4.0"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32777b0b3f6538d9d2e012b3fad85c7e4b9244b5958d04a6415f4333782b7a77"
checksum = "0dd418ac3c91caa4032d37cb80ff0d44e2ebe637b2fb243b6234bf89cdac4901"
dependencies = [
"anyhow",
"once_cell",
@@ -1142,9 +1311,9 @@ dependencies = [
[[package]]
name = "protobuf-parse"
version = "3.4.0"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96cb37955261126624a25b5e6bda40ae34cf3989d52a783087ca6091b29b5642"
checksum = "9d39b14605eaa1f6a340aec7f320b34064feb26c93aec35d6a9a2272a8ddfa49"
dependencies = [
"anyhow",
"indexmap 1.9.3",
@@ -1158,9 +1327,9 @@ dependencies = [
[[package]]
name = "protobuf-support"
version = "3.4.0"
version = "3.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1ed294a835b0f30810e13616b1cd34943c6d1e84a8f3b0dcfe466d256c3e7e7"
checksum = "a5d4d7b8601c814cfb36bcebb79f0e61e45e1e93640cf778837833bbed05c372"
dependencies = [
"thiserror",
]
@@ -1364,18 +1533,104 @@ dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "rustls"
version = "0.23.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05cff451f60db80f490f3c182b77c35260baace73209e9cdbbe526bfe3a4d402"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-native-certs"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a88d6d420651b496bdd98684116959239430022a115c1240e6c3993be0b15fba"
dependencies = [
"openssl-probe",
"rustls-pemfile",
"rustls-pki-types",
"schannel",
"security-framework",
]
[[package]]
name = "rustls-pemfile"
version = "2.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d"
dependencies = [
"base64",
"rustls-pki-types",
]
[[package]]
name = "rustls-pki-types"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d"
[[package]]
name = "rustls-webpki"
version = "0.102.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "ryu"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
[[package]]
name = "schannel"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534"
dependencies = [
"windows-sys 0.52.0",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "security-framework"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0"
dependencies = [
"bitflags 2.5.0",
"core-foundation",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]]
name = "serde"
version = "1.0.198"
@@ -1430,6 +1685,17 @@ dependencies = [
"unsafe-libyaml",
]
[[package]]
name = "sha1"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha2"
version = "0.10.8"
@@ -1476,6 +1742,15 @@ dependencies = [
"rand_core",
]
[[package]]
name = "slab"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
]
[[package]]
name = "smallvec"
version = "1.13.2"
@@ -1484,9 +1759,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]]
name = "socket2"
version = "0.5.6"
version = "0.5.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05ffd9c0a93b7543e062e759284fcf5f5e3b098501104bfbdde4d404db792871"
checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c"
dependencies = [
"libc",
"windows-sys 0.52.0",
@@ -1572,6 +1847,15 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "sys-locale"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e801cf239ecd6ccd71f03d270d67dd53d13e90aab208bf4b8fe4ad957ea949b0"
dependencies = [
"libc",
]
[[package]]
name = "tempfile"
version = "3.10.1"
@@ -1614,6 +1898,21 @@ dependencies = [
"winapi",
]
[[package]]
name = "tinyvec"
version = "1.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c55115c6fbe2d2bef26eb09ad74bde02d8255476fc0c7b515ef09fbb35742d82"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.37.0"
@@ -1644,6 +1943,34 @@ dependencies = [
"syn 2.0.60",
]
[[package]]
name = "tokio-rustls"
version = "0.26.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4"
dependencies = [
"rustls",
"rustls-pki-types",
"tokio",
]
[[package]]
name = "tokio-tungstenite"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6989540ced10490aaf14e6bad2e3d33728a2813310a0c71d1574304c49631cd"
dependencies = [
"futures-util",
"log",
"rustls",
"rustls-native-certs",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tungstenite",
"webpki-roots",
]
[[package]]
name = "tun"
version = "0.1.0"
@@ -1653,10 +1980,31 @@ dependencies = [
"libloading",
"log",
"rand",
"sha2",
"widestring",
"winapi",
]
[[package]]
name = "tungstenite"
version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2e2ce1e47ed2994fd43b04c8f618008d4cabdd5ee34027cf14f9d918edd9c8"
dependencies = [
"byteorder",
"bytes",
"data-encoding",
"http 1.1.0",
"httparse",
"log",
"rand",
"rustls",
"rustls-pki-types",
"sha1",
"thiserror",
"utf-8",
]
[[package]]
name = "typemap-ors"
version = "1.0.0"
@@ -1672,6 +2020,12 @@ version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]]
name = "unicode-bidi"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08f95100a766bf4f8f28f90d77e0a5461bbdb219042e7679bebe79004fed8d75"
[[package]]
name = "unicode-ident"
version = "1.0.12"
@@ -1679,10 +2033,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "unicode-width"
version = "0.1.11"
name = "unicode-normalization"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85"
checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-width"
version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d"
[[package]]
name = "universal-hash"
@@ -1715,6 +2078,23 @@ version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "url"
version = "2.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
]
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "uuid"
version = "1.8.0"
@@ -1738,7 +2118,7 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "vn-link"
version = "1.2.10"
version = "1.2.14"
dependencies = [
"anyhow",
"crossbeam-utils",
@@ -1751,7 +2131,7 @@ dependencies = [
[[package]]
name = "vn-link-cli"
version = "1.2.10"
version = "1.2.14"
dependencies = [
"common",
"log",
@@ -1761,7 +2141,7 @@ dependencies = [
[[package]]
name = "vnt"
version = "1.2.10"
version = "1.2.14"
dependencies = [
"aes",
"aes-gcm",
@@ -1777,12 +2157,15 @@ dependencies = [
"dns-parser",
"ecb",
"fnv",
"futures-util",
"igd",
"libc",
"libloading",
"libsm",
"log",
"lz4_flex",
"mio",
"network-interface",
"openssl-sys",
"packet",
"parking_lot",
@@ -1792,23 +2175,27 @@ dependencies = [
"rand",
"ring",
"rsa",
"rustls",
"sha2",
"socket2",
"spki",
"stun-format",
"thiserror",
"tokio",
"tokio-tungstenite",
"tun",
"windows-sys 0.59.0",
"zstd",
]
[[package]]
name = "vnt-cli"
version = "1.2.10"
version = "1.2.14"
dependencies = [
"anyhow",
"chrono",
"common",
"console",
"log",
"rand",
"signal-hook",
@@ -1877,6 +2264,15 @@ version = "0.2.92"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96"
[[package]]
name = "webpki-roots"
version = "0.26.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bd7c23921eeb1713a4e851530e9b9756e4fb0e89978582942612524cf09f01cd"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "which"
version = "4.4.2"
@@ -1895,6 +2291,12 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7219d36b6eac893fa81e84ebe06485e7dcbb616177469b142df14f1f4deb1311"
[[package]]
name = "wildmatch"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f44b95f62d34113cf558c93511ac93027e03e9c29a60dd0fd70e6e025c7270a"
[[package]]
name = "winapi"
version = "0.3.9"
@@ -1923,7 +2325,7 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-targets 0.52.5",
"windows-targets 0.52.6",
]
[[package]]
@@ -1941,7 +2343,16 @@ version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets 0.52.5",
"windows-targets 0.52.6",
]
[[package]]
name = "windows-sys"
version = "0.59.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
dependencies = [
"windows-targets 0.52.6",
]
[[package]]
@@ -1961,18 +2372,18 @@ dependencies = [
[[package]]
name = "windows-targets"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm 0.52.5",
"windows_aarch64_msvc 0.52.5",
"windows_i686_gnu 0.52.5",
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
"windows_i686_gnullvm",
"windows_i686_msvc 0.52.5",
"windows_x86_64_gnu 0.52.5",
"windows_x86_64_gnullvm 0.52.5",
"windows_x86_64_msvc 0.52.5",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
[[package]]
@@ -1983,9 +2394,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
@@ -1995,9 +2406,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
@@ -2007,15 +2418,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
[[package]]
name = "windows_i686_gnu"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
@@ -2025,9 +2436,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
[[package]]
name = "windows_i686_msvc"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
@@ -2037,9 +2448,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
@@ -2049,9 +2460,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
@@ -2061,9 +2472,24 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.5"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "xml-rs"
version = "0.8.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791978798f0597cfc70478424c2b4fdc2b7a8024aaff78497ef00f24ef674193"
[[package]]
name = "xmltree"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7d8a75eaf6557bb84a65ace8609883db44a29951042ada9b393151532e41fcb"
dependencies = [
"xml-rs",
]
[[package]]
name = "yasna"
+41 -133
View File
@@ -1,12 +1,12 @@
# Vnt
# VNT
A virtual network tool (VPN)
🚀An efficient VPN
将不同网络下的多个设备虚拟到一个局域网下
🚀一个简单、高效、能快速组建虚拟局域网的工具
### vnt-cli参数详解 [参数说明](https://github.com/lbl8603/vnt/blob/main/vnt-cli/README.md)
### vnt-cli参数详解 [参数说明](https://github.com/vnt-dev/vnt/blob/main/vnt-cli/README.md)
### 快速使用
### 快速开始
1. 指定一个token,在多台设备上运行该程序,例如:
```shell
@@ -39,27 +39,26 @@ A virtual network tool (VPN)
```
4. 最后可以用虚拟ip实现设备间相互访问
<img width="506" alt="ssh" src="https://raw.githubusercontent.com/lbl8603/vnt/main/documents/img/ssh.jpg">
<img width="506" alt="ssh" src="https://raw.githubusercontent.com/vnt-dev/vnt/main/documents/img/ssh.jpg">
5. 帮助,使用-h命令查看
### 更多玩法
1. 和远程桌面(如mstsc)搭配,超低延迟的体验
2. 安装samba服务,共享磁盘
3. 搭配公网服务器nginx反向代理,在公网访问内网文件或服务
4. 点对网,访问内网其他机器、IP代理(结合启动参数'-i'和'-o')
### 使用须知
- token的作用是标识一个虚拟局域网,当使用公共服务器时,建议使用一个唯一值当token(比如uuid),否则有可能连接到其他人创建的虚拟局域网中
- 默认使用公共服务器做注册和中继,目前的配置是2核4G 4Mbps,有需要再扩展~
- 需要root/管理员权限
- vnt-cli需要使用命令行运行
- Mac和Linux下需要加可执行权限(例如:chmod +x ./vnt-cli)
- 可以自己搭注册和中继服务器([server](https://github.com/lbl8603/vnts))
- vnt使用stun服务器探测网络NAT类型,默认使用谷歌和腾讯的stun服务器,也可自己搭建(-e参数指定)
- 可以自己搭中继服务器([server](https://github.com/vnt-dev/vnts))
### 编译
### 直接使用
[**下载release文件**](https://github.com/vnt-dev/vnt/releases)
[**帮助文档**](https://rustvnt.com)
### 自行编译
<details> <summary>点击展开</summary>
前提条件:安装rust编译环境([install rust](https://www.rust-lang.org/zh-CN/tools/install))
@@ -91,82 +90,9 @@ features说明
| file_config | yaml配置文件 | 是 |
| lz4 | lz4压缩 | 是 |
| zstd | zstd压缩 | 否 |
### 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
```
| upnp | upnp协议 | 否 |
| ws | ws协议 | 是 |
| wss | wss协议 | 是 |
</details>
@@ -176,60 +102,38 @@ sudo pfctl -f /etc/pf.conf -e
- Linux
- 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)
- 可选择使用tap网卡 依赖tap-windows([win-tap](https://build.openvpn.net/downloads/releases/))(建议使用版本9.24.7)
- Android
### GUI
支持安卓和Windows [下载](https://github.com/lbl8603/VntApp/releases/)
支持安卓和Windows [下载](https://github.com/vnt-dev/VntApp/releases/)
### 特性
- IP层数据转发
- tun虚拟网卡
- tap虚拟网卡
- NAT穿透
- 点对点穿透
- 服务端中继转发
- 客户端中继转发
- IP代理
- IP代理(点对点、点对网)
- p2p组播/广播
- 客户端数据加密
- 服务端数据加密
- 客户端数据加密(`aes-gcm`、`chacha20-poly1305`等多种加密算法)
- 服务端数据加密(`rsa` + `aes-gcm`)
- 多通道UDP应对QOS
- 支持TCP、UDP、WebSocket等多种协议
- 支持数据压缩
### 结构
### 更多玩法
<details> <summary>展开</summary>
<pre>
0 15 31
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|e |s |unused| 版本(4) | 协议(8) | 上层协议(8) |初始ttl(4)|生存时间(4) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 源ip地址(32) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 目的ip地址(32) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| 数据体(n) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| 指纹(96) |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
注:
1. e为是否加密标志,s为服务端通信包标志,unused占两位未使用;
2. 开启加密时,数据体为加密后的密文(加密方式取决于密码长度和加密模式),
且会存在指纹,指纹使用sha256生成,用于对数据包完整性和真实性的校验
</pre>
</details>
1. 和远程桌面(如mstsc)搭配,超低延迟的体验
2. 安装samba服务,共享磁盘
3. 点对网,访问内网其他机器、IP代理(结合启动参数'-i'和'-o')
### Todo
- 桌面UI(测试中)
- ~~桌面UI(已支持)~~
- 使用FEC、ARQ等方式提升弱网环境的稳定性
### 常见问题
@@ -287,11 +191,15 @@ vnt默认使用10.26.0.0/24网段,和本地网络适配器的ip冲突
对VNT有任何问题均可以加群联系作者
QQ: 1034868233
QQ群1: 1034868233(满人)
QQ群2: 950473757
### 赞助
如果VNT对你有帮助,欢迎打赏作者
<img width="300" alt="" src="https://github.com/lbl8603/vnt/assets/49143209/0d3a7311-43fc-4ed7-9507-863b5d69b6b2">
<img width="300" alt="" src="https://github.com/vnt-dev/vnt/assets/49143209/0d3a7311-43fc-4ed7-9507-863b5d69b6b2">
### 其他
@@ -302,6 +210,6 @@ QQ: 1034868233
### 参与贡献
<a href="https://github.com/lbl8603/vnt/graphs/contributors">
<img src="https://contrib.rocks/image?repo=lbl8603/vnt" />
<a href="https://github.com/vnt-dev/vnt/graphs/contributors">
<img src="https://contrib.rocks/image?repo=vnt-dev/vnt" />
</a>
+5 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "common"
version = "1.2.10"
version = "1.2.14"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -16,6 +16,7 @@ serde_yaml = "0.9.32"
getopts = "0.2.21"
gethostname = "0.4.3"
uuid = { version = "1.8.0", features = ["v4"] }
sys-locale = "0.3.1"
[features]
default = []
@@ -32,7 +33,9 @@ ip_proxy = ["vnt/ip_proxy"]
port_mapping = ["vnt/port_mapping"]
lz4 = ["vnt/lz4_compress"]
zstd = ["vnt/zstd_compress"]
upnp = ["vnt/upnp"]
ws = ["vnt/ws"]
wss = ["vnt/wss"]
command = []
file_config = []
log = ["log4rs"]
+3 -2
View File
@@ -10,7 +10,7 @@ impl VntCallback for VntHandler {
fn success(&self) {
println!(" {} ", style("====== Connect Successfully ======").green())
}
#[cfg(feature = "vnt-model")]
#[cfg(feature = "integrated_tun")]
fn create_tun(&self, info: vnt::DeviceInfo) {
println!("create_tun {}", info)
}
@@ -37,7 +37,8 @@ impl VntCallback for VntHandler {
| ErrorType::AddressExhausted
| ErrorType::IpAlreadyExists
| ErrorType::InvalidIp
| ErrorType::LocalIpExists => {
| ErrorType::LocalIpExists
| ErrorType::FailedToCrateDevice => {
self.stop();
}
_ => {}
+220 -57
View File
@@ -5,10 +5,12 @@ use crate::{config, generated_serial_number};
use anyhow::anyhow;
use console::style;
use getopts::Options;
use std::collections::HashMap;
use std::io;
use std::net::Ipv4Addr;
use std::path::PathBuf;
use std::str::FromStr;
use sys_locale::get_locale;
use vnt::channel::punch::PunchModel;
use vnt::channel::UseChannelType;
use vnt::cipher::CipherModel;
@@ -56,7 +58,6 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
opts.optopt("w", "", "客户端加密", "<password>");
opts.optflag("W", "", "服务端加密");
opts.optopt("u", "", "自定义mtu(默认为1430)", "<mtu>");
opts.optflag("", "tcp", "tcp");
opts.optopt("", "ip", "指定虚拟ip", "<ip>");
opts.optflag("", "relay", "仅使用服务器转发");
opts.optopt("", "par", "任务并行度(必须为正整数)", "<parallel>");
@@ -75,12 +76,17 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
opts.optmulti("", "vnt-mapping", "vnt-mapping", "<mapping>");
opts.optopt("f", "", "配置文件", "<conf>");
opts.optopt("", "compressor", "压缩算法", "<lz4>");
opts.optopt("", "local-dev", "指定本地ipv4网卡名称", "<NAME>");
opts.optflag("", "disable-stats", "关闭流量统计");
opts.optflag("", "allow-wg", "允许接入WireGuard");
//"后台运行时,查看其他设备列表"
opts.optflag("", "add", "后台运行时,添加地址");
opts.optflag("", "list", "后台运行时,查看其他设备列表");
opts.optflag("", "all", "后台运行时,查看其他设备完整信息");
opts.optflag("", "info", "后台运行时,查看当前设备信息");
opts.optflag("", "route", "后台运行时,查看数据转发路径");
opts.optflag("", "chart_a", "后台运行时,查看流量统计");
opts.optopt("", "chart_b", "后台运行时,查看流量统计", "<IP>");
opts.optflag("", "stop", "停止后台运行");
opts.optflag("h", "help", "帮助");
let matches = match opts.parse(&args[1..]) {
@@ -112,6 +118,16 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
command::command(command::CommandEnum::All);
return Ok(None);
}
#[cfg(feature = "command")]
if matches.opt_present("chart_a") {
command::command(command::CommandEnum::ChartA);
return Ok(None);
}
#[cfg(feature = "command")]
if let Some(v) = matches.opt_str("chart_b") {
command::command(command::CommandEnum::ChartB(v));
return Ok(None);
}
let conf = matches.opt_str("f");
let (config, vnt_link_config, cmd) = if conf.is_some() {
match config::read_config(&conf.unwrap()) {
@@ -156,9 +172,9 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
let mut stun_server = matches.opt_strs("e");
if stun_server.is_empty() {
stun_server.push("stun1.l.google.com:19302".to_string());
stun_server.push("stun2.l.google.com:19302".to_string());
stun_server.push("stun.miwifi.com:3478".to_string());
for x in config::PUB_STUN {
stun_server.push(x.to_string());
}
}
let dns = matches.opt_strs("dns");
let in_ip = matches.opt_strs("i");
@@ -213,7 +229,6 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
return Err(anyhow::anyhow!("'--ip {}' invalid", virtual_ip));
}
}
let tcp_channel = matches.opt_present("tcp");
let relay = matches.opt_present("relay");
let cipher_model = match matches.opt_get::<CipherModel>("model") {
@@ -269,6 +284,10 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
#[cfg(feature = "port_mapping")]
let port_mapping_list = matches.opt_strs("mapping");
let vnt_mapping_list = matches.opt_strs("vnt-mapping");
let local_dev: Option<String> = matches.opt_get("local-dev").unwrap();
let disable_stats = matches.opt_present("disable-stats");
let allow_wire_guard = matches.opt_present("allow-wg");
let compressor = if let Some(compressor) = matches.opt_str("compressor").as_ref() {
Compressor::from_str(compressor)
.map_err(|e| anyhow!("{}", e))
@@ -276,7 +295,7 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
} else {
Compressor::None
};
let config = match Config::new(
let config = Config::new(
#[cfg(feature = "integrated_tun")]
#[cfg(target_os = "windows")]
tap,
@@ -290,7 +309,6 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
out_ip,
password,
mtu,
tcp_channel,
virtual_ip,
#[cfg(feature = "integrated_tun")]
#[cfg(feature = "ip_proxy")]
@@ -309,13 +327,10 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
#[cfg(feature = "port_mapping")]
port_mapping_list,
compressor,
) {
Ok(config) => config,
Err(e) => {
println!("config.toml error: {}", e);
std::process::exit(1);
}
};
!disable_stats,
allow_wire_guard,
local_dev,
)?;
(config, vnt_mapping_list, cmd)
};
println!("version {}", vnt::VNT_VERSION);
@@ -328,37 +343,124 @@ pub fn parse_args_config() -> anyhow::Result<Option<(Config, Vec<String>, bool)>
Ok(Some((config, vnt_link_config, cmd)))
}
fn get_description(key: &str, language: &str) -> String {
// 设置一个全局的映射来存储中英文对照
let descriptions: HashMap<&str, (&str, &str)> = [
("-k <token>", ("使用相同的token,就能组建一个局域网络", "Use the same token to form a local network")),
("-n <name>", ("给设备一个名字,便于区分不同设备,默认使用系统版本", "Give the device a name to distinguish it, defaults to system version")),
("-d <id>", ("设备唯一标识符,不使用--ip参数时,服务端凭此参数分配虚拟ip,注意不能重复", "Device unique identifier, used by the server to allocate virtual IP when --ip parameter is not used, must be unique")),
("-s <server>", ("注册和中继服务器地址,协议支持使用tcp://和ws://和wss://,默认为udp://", "Registration and relay server address, protocols support using tcp://, ws://, and wss://, default is udp://")),
("-e <stun-server>", ("stun服务器,用于探测NAT类型,可使用多个地址,如-e stun.miwifi.com -e turn.cloudflare.com", "STUN server for detecting NAT type, can specify multiple addresses, e.g., -e stun.miwifi.com -e turn.cloudflare.com")),
("-a", ("使用tap模式,默认使用tun模式,使用tap时需要配合'--nic'参数指定tap网卡", "Use tap mode, default is tun mode, specify '--nic' parameter with tap network card")),
("-i <in-ip>", ("配置点对网(IP代理)时使用,-i 192.168.0.0/24,10.26.0.3表示允许接收网段192.168.0.0/24的数据并转发到10.26.0.3,可指定多个网段", "Used when configuring point-to-point network (IP proxy), -i 192.168.0.0/24,10.26.0.3 allows receiving data from subnet 192.168.0.0/24 and forwarding to 10.26.0.3, specify multiple subnets")),
("-o <out-ip>", ("配置点对网时使用,-o 192.168.0.0/24表示允许将数据转发到192.168.0.0/24,可指定多个网段", "Used when configuring point-to-point network, -o 192.168.0.0/24 allows forwarding data to 192.168.0.0/24, specify multiple subnets")),
("-w <password>", ("使用该密码生成的密钥对客户端数据进行加密,并且服务端无法解密,使用相同密码的客户端才能通信", "Encrypt client data with keys generated by this password, server cannot decrypt, clients must use the same password to communicate")),
("-W", ("加密当前客户端和服务端通信的数据,请留意服务端指纹是否正确", "Encrypt the data currently being communicated between the client and server, please pay attention to whether the server fingerprint is correct")),
("-u <mtu>", ("自定义mtu(默认为1420)", "Customize MTU (default is 1420)")),
("-f <conf_file>", ("读取配置文件中的配置", "Read configuration from file")),
("--ip <ip>", ("指定虚拟ip,指定的ip不能和其他设备重复,必须有效并且在服务端所属网段下,默认情况由服务端分配", "Specify virtual IP, must be unique and valid within server subnet, by default allocated by server")),
("--model <model>", ("加密模式(默认aes_gcm),可选值", "Encryption mode (default aes_gcm), options ")),
("--finger", ("增加数据指纹校验,可增加安全性,如果服务端开启指纹校验,则客户端也必须开启", "Add data fingerprint verification for increased security, client must enable if server does")),
("--punch <punch>", ("取值ipv4/ipv6/ipv4-tcp/ipv4-udp/ipv6-tcp/ipv6-udp/all,ipv4表示仅使用ipv4打洞", "Values ipv4/ipv6/ipv4-tcp/ipv4-udp/ipv6-tcp/ipv6-udp/all, ipv4 for IPv4 hole punching only")),
("--ports <port,port>", ("取值0~65535,指定本地监听的一组端口,默认监听两个随机端口,使用过多端口会增加网络负担", "Values 0~65535, specify a group of local listening ports, defaults to two random ports, using many ports increases network load")),
("--cmd", ("开启交互式命令,使用此参数开启控制台输入", "Enable interactive command mode, use this parameter to enable console input")),
("--no-proxy", ("关闭内置代理,如需点对网则需要配置网卡NAT转发", "Disable built-in proxy, configure network card NAT forwarding for point-to-point networking")),
("--first-latency", ("优先低延迟的通道,默认情况优先使用p2p通道", "Prioritize low-latency channels, defaults to prioritizing p2p channel")),
("--use-channel <p2p>", ("使用通道 relay/p2p/all,默认两者都使用", "Use channel relay/p2p/all, defaults to using both")),
("--nic <tun0>", ("指定虚拟网卡名称", "Specify virtual network card name")),
("--packet-loss <0>", ("模拟丢包,取值0~1之间的小数,程序会按设定的概率主动丢包,可用于模拟弱网", "Simulate packet loss, value between 0 and 1, program actively drops packets based on set probability, useful for simulating weak networks")),
("--packet-delay <0>", ("模拟延迟,正整数,单位毫秒,程序将根据设定值延迟发送数据包,可用于模拟弱网", "Simulate latency, integer, in milliseconds (ms). The program will delay sending packets according to the set value and can be used to simulate weak networks")),
("--dns <host:port>", ("DNS服务器地址,可使用多个dns,不指定时使用系统解析", "DNS server address, can specify multiple DNS servers, defaults to system resolution if not specified")),
("--mapping <mapping>", ("端口映射,例如 --mapping udp:0.0.0.0:80-domain:80 映射目标是本地路由能访问的设备", "Port mapping, e.g., --mapping udp:0.0.0.0:80-domain:80 maps to a device accessible by local routing")),
("--compressor-all <lz4>", ("启用压缩,可选值lz4/zstd<,level>,level为压缩级别,例如 --compressor lz4 或--compressor zstd,10", "Enable compression, options lz4/zstd<,level>, level is compression level, e.g., --compressor lz4 or --compressor zstd,10")),
("--compressor-lz4 <lz4>", ("启用压缩,可选值lz4,例如 --compressor lz4", "Enable compression, option lz4, e.g., --compressor lz4")),
("--compressor-zstd <zstd>", ("启用压缩,可选值zstd<,level>,level为压缩级别,例如 --compressor zstd,10", "Enable compression, options zstd<,level>, level is compression level, e.g., --compressor zstd,10")),
("--vnt-mapping <x>", ("vnt地址映射,例如 --vnt-mapping tcp:80-10.26.0.10:80 映射目标是vnt网络或其子网中的设备", "VNT address mapping, e.g., --vnt-mapping tcp:80-10.26.0.10:80 maps to a device in VNT network or its subnet")),
("--local-dev", ("本地出口网卡的名称", "name of local export network card")),
("--disable-stats", ("关闭流量统计", "Disable traffic statistics")),
("--allow-wg", ("允许接入WireGuard客户端", "Allow access to WireGuard client")),
("--list", ("后台运行时,查看其他设备列表", "View list of other devices when running in background")),
("--all", ("后台运行时,查看其他设备完整信息", "View complete information of other devices when running in background")),
("--info", ("后台运行时,查看当前设备信息", "View information of current device when running in background")),
("--route", ("后台运行时,查看数据转发路径", "View data forwarding path when running in background")),
("--chart_a", ("后台运行时,查看所有IP的流量统计", "View traffic statistics of all IPs when running in background")),
("--chart_b <IP>", ("后台运行时,查看单个IP的历史流量", "View historical traffic of a single IP when running in background")),
("--stop", ("停止后台运行", "Stop running in background"))
// ... 其他选项
]
.iter()
.cloned()
.collect();
if let Some(&(zh, en)) = descriptions.get(key) {
if language.starts_with("zh") {
return zh.to_string(); // 返回 String 类型
}
// 默认返回英文
return en.to_string(); // 返回 String 类型
}
// 如果没有找到对应的键,则返回空字符串
String::new()
}
fn print_usage(program: &str, _opts: Options) {
// 获取系统语言 Locale::user_default().unwrap_or_else(|_| Locale::default());
let language = get_locale().unwrap_or_else(|| String::from("en-US"));
println!("Usage: {} [options]", program);
println!("version:{}", vnt::VNT_VERSION);
println!("Serial:{}", generated_serial_number::SERIAL_NUMBER);
println!("Options:");
println!(
" -k <token> {}",
green("使用相同的token,就能组建一个局域网络".to_string())
green(get_description("-k <token>", &language).to_string())
);
println!(
" -n <name> {}",
get_description("-n <name>", &language)
);
println!(
" -d <id> {}",
get_description("-d <id>", &language)
);
println!(
" -s <server> {}",
get_description("-s <server>", &language)
);
println!(
" -e <stun-server> {}",
get_description("-e <stun-server>", &language)
);
println!(" -n <name> 给设备一个名字,便于区分不同设备,默认使用系统版本");
println!(" -d <id> 设备唯一标识符,不使用--ip参数时,服务端凭此参数分配虚拟ip,注意不能重复");
println!(" -s <server> 注册和中继服务器地址,以'TXT:'开头表示解析TXT记录");
println!(" -e <stun-server> stun服务器,用于探测NAT类型,可使用多个地址,如-e stun1.l.google.com -e stun2.l.google.com");
#[cfg(target_os = "windows")]
#[cfg(feature = "integrated_tun")]
println!(" -a {}", get_description("-a", &language));
println!(
" -a 使用tap模式,默认使用tun模式,使用tap时需要配合'--nic'参数指定tap网卡"
" -i <in-ip> {}",
get_description("-i <in-ip>", &language)
);
println!(
" -o <out-ip> {}",
get_description("-o <out-ip>", &language)
);
println!(
" -w <password> {}",
get_description("-w <password>", &language)
);
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,可指定多个网段");
println!(" -w <password> 使用该密码生成的密钥对客户端数据进行加密,并且服务端无法解密,使用相同密码的客户端才能通信");
#[cfg(feature = "server_encrypt")]
println!(" -W 加密当前客户端和服务端通信的数据,请留意服务端指纹是否正确");
println!(" -u <mtu> 自定义mtu(不加密默认为1450,加密默认为1410)");
println!(" -W {}", get_description("-W", &language));
println!(
" -u <mtu> {}",
get_description("-u <mtu>", &language)
);
#[cfg(feature = "file_config")]
println!(" -f <conf_file> 读取配置文件中的配置");
println!(
" -f <conf_file> {}",
get_description("-f <conf_file>", &language)
);
println!(" --tcp 和服务端使用tcp通信,默认使用udp,遇到udp qos时可指定使用tcp");
println!(" --ip <ip> 指定虚拟ip,指定的ip不能和其他设备重复,必须有效并且在服务端所属网段下,默认情况由服务端分配");
println!(
" --ip <ip> {}",
get_description("--ip <ip>", &language)
);
let mut enums = String::new();
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
enums.push_str("/aes_gcm");
@@ -372,7 +474,8 @@ fn print_usage(program: &str, _opts: Options) {
enums.push_str("/sm4_cbc");
enums.push_str("/xor");
println!(
" --model <model> 加密模式(默认aes_gcm),可选值{}",
" --model <model> {}{}",
get_description("--model <model>", &language),
&enums[1..]
);
#[cfg(any(
@@ -383,43 +486,95 @@ fn print_usage(program: &str, _opts: Options) {
feature = "aes_ecb",
feature = "sm4_cbc"
))]
println!(" --finger 增加数据指纹校验,可增加安全性,如果服务端开启指纹校验,则客户端也必须开启");
println!(" --punch <punch> 取值ipv4/ipv6/all,ipv4表示仅使用ipv4打洞");
println!(" --ports <port,port> 取值0~65535,指定本地监听的一组端口,默认监听两个随机端口,使用过多端口会增加网络负担");
println!(
" --finger {}",
get_description("--finger", &language)
);
println!(
" --punch <punch> {}",
get_description("--punch <punch>", &language)
);
println!(
" --ports <port,port> {}",
get_description("--ports <port,port>", &language)
);
#[cfg(feature = "command")]
println!(" --cmd 开启交互式命令,使用此参数开启控制台输入");
println!(
" --cmd {}",
get_description("--cmd", &language)
);
#[cfg(feature = "ip_proxy")]
#[cfg(feature = "integrated_tun")]
println!(" --no-proxy 关闭内置代理,如需点对网则需要配置网卡NAT转发");
println!(" --first-latency 优先低延迟的通道,默认情况优先使用p2p通道");
println!(" --use-channel <p2p> 使用通道 relay/p2p/all,默认两者都使用");
#[cfg(not(feature = "vn-link-model"))]
println!(" --nic <tun0> 指定虚拟网卡名称");
println!(" --packet-loss <0> 模拟丢包,取值0~1之间的小数,程序会按设定的概率主动丢包,可用于模拟弱网");
println!(
" --packet-delay <0> 模拟延迟,整数,单位毫秒(ms),程序会按设定的值延迟发包,可用于模拟弱网"
" --no-proxy {}",
get_description("--no-proxy", &language)
);
println!(
" --first-latency {}",
get_description("--first-latency", &language)
);
println!(
" --use-channel <p2p> {}",
get_description("--use-channel <p2p>", &language)
);
#[cfg(not(feature = "vn-link-model"))]
println!(
" --nic <tun0> {}",
get_description("--nic <tun0>", &language)
);
println!(
" --packet-loss <0> {}",
get_description("--packet-loss <0>", &language)
);
println!(
" --packet-delay <0> {}",
get_description("--packet-delay <0>", &language)
);
println!(
" --dns <host:port> {}",
get_description("--dns <host:port>", &language)
);
println!(" --dns <host:port> DNS服务器地址,可使用多个dns,不指定时使用系统解析");
#[cfg(feature = "port_mapping")]
println!(" --mapping <mapping> 端口映射,例如 --mapping udp:0.0.0.0:80-domain:80 映射目标是本地路由能访问的设备");
println!(
" --mapping <mapping> {}",
get_description("--mapping <mapping>", &language)
);
#[cfg(all(feature = "lz4", feature = "zstd"))]
println!(" --compressor <lz4> 启用压缩,可选值lz4/zstd<,level>,level为压缩级别,例如 --compressor lz4 或--compressor zstd,10");
println!(
" --compressor <lz4> {}",
get_description("--compressor-all <lz4>", &language)
);
#[cfg(feature = "lz4")]
#[cfg(not(feature = "zstd"))]
println!(" --compressor <lz4> 启用压缩,可选值lz4,例如 --compressor lz4");
println!(
" --compressor <lz4> {}",
get_description("--compressor-lz4 <lz4>", &language)
);
#[cfg(feature = "zstd")]
#[cfg(not(feature = "lz4"))]
println!(" --compressor <zstd> 启用压缩,可选值zstd<,level>,level为压缩级别,例如 --compressor zstd,10");
println!(
" --compressor <zstd> {}",
get_description("--compressor-zstd <zstd>", &language)
);
#[cfg(not(feature = "integrated_tun"))]
println!(
" --vnt-mapping <x> {}",
green(
"vnt地址映射,例如 --vnt-mapping tcp:80-10.26.0.10:80 映射目标是vnt网络或其子网中的设备"
.to_string()
)
green(get_description("--vnt-mapping <x>", &language).to_string())
);
println!(
" --local-dev <NAME> {}",
get_description("--local-dev", &language)
);
println!(
" --disable-stats {}",
get_description("--disable-stats", &language)
);
println!(
" --allow-wg {}",
get_description("--allow-wg", &language)
);
println!();
#[cfg(feature = "command")]
@@ -431,26 +586,34 @@ fn print_usage(program: &str, _opts: Options) {
// );
println!(
" --list {}",
yellow("后台运行时,查看其他设备列表".to_string())
yellow(get_description("--list", &language).to_string())
);
println!(
" --all {}",
yellow("后台运行时,查看其他设备完整信息".to_string())
yellow(get_description("--all", &language).to_string())
);
println!(
" --info {}",
yellow("后台运行时,查看当前设备信息".to_string())
yellow(get_description("--info", &language).to_string())
);
println!(
" --route {}",
yellow("后台运行时,查看数据转发路径".to_string())
yellow(get_description("--route", &language).to_string())
);
println!(
" --chart_a {}",
yellow(get_description("--chart_a", &language).to_string())
);
println!(
" --chart_b <IP> {}",
yellow(get_description("--chart_b <IP>", &language).to_string())
);
println!(
" --stop {}",
yellow("停止后台运行".to_string())
yellow(get_description("--stop", &language).to_string())
);
}
println!(" -h, --help 帮助");
println!(" -h, --help display help information(显示帮助信息)");
}
fn green(str: String) -> impl std::fmt::Display {
+12 -1
View File
@@ -4,7 +4,7 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket};
use std::str::FromStr;
use std::time::Duration;
use crate::command::entity::{DeviceItem, Info, RouteItem};
use crate::command::entity::{ChartA, ChartB, DeviceItem, Info, RouteItem};
pub struct CommandClient {
buf: Vec<u8>,
@@ -53,6 +53,17 @@ impl CommandClient {
pub fn info(&mut self) -> io::Result<Info> {
self.send_cmd(b"info")
}
pub fn chart_a(&mut self) -> io::Result<ChartA> {
self.send_cmd(b"chart_a")
}
pub fn chart_b(&mut self, input: &str) -> io::Result<ChartB> {
let cmd = if input.is_empty() {
"chart_b".to_string()
} else {
format!("chart_b:{}", input)
};
self.send_cmd(cmd.as_bytes())
}
fn send_cmd<'a, V: Deserialize<'a>>(&'a mut self, cmd: &[u8]) -> io::Result<V> {
self.udp.send(cmd)?;
let len = self.udp.recv(&mut self.buf)?;
+24 -2
View File
@@ -1,5 +1,7 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::net::{Ipv4Addr, SocketAddr};
#[derive(Serialize, Deserialize, Debug)]
pub struct Info {
pub name: String,
@@ -12,11 +14,11 @@ pub struct Info {
pub public_ips: String,
pub local_addr: String,
pub ipv6_addr: String,
pub up: u64,
pub down: u64,
pub port_mapping_list: Vec<(bool, SocketAddr, String)>,
pub in_ips: Vec<(u32, u32, Ipv4Addr)>,
pub out_ips: Vec<(u32, u32)>,
pub udp_listen_addr: Vec<String>,
pub tcp_listen_addr: String,
}
#[derive(Serialize, Deserialize, Debug)]
@@ -43,4 +45,24 @@ pub struct DeviceItem {
pub client_secret_hash: Vec<u8>,
pub current_client_secret: bool,
pub current_client_secret_hash: Vec<u8>,
pub wire_guard: bool,
}
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ChartA {
pub disable_stats: bool,
pub up_total: u64,
pub down_total: u64,
pub up_map: HashMap<Ipv4Addr, u64>,
pub down_map: HashMap<Ipv4Addr, u64>,
}
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct ChartB {
pub disable_stats: bool,
pub ip: Option<Ipv4Addr>,
pub up_total: u64,
pub up_list: Vec<usize>,
pub down_total: u64,
pub down_list: Vec<usize>,
}
+123 -12
View File
@@ -1,7 +1,10 @@
use std::collections::HashSet;
use std::io;
use std::net::Ipv4Addr;
use vnt::channel::ConnectProtocol;
use vnt::core::Vnt;
use crate::command::entity::{DeviceItem, Info, RouteItem};
use crate::command::entity::{ChartA, ChartB, DeviceItem, Info, RouteItem};
use crate::console_out;
pub mod client;
@@ -13,6 +16,8 @@ pub enum CommandEnum {
List,
All,
Info,
ChartA,
ChartB(String),
Stop,
}
@@ -20,7 +25,9 @@ pub fn command_str(cmd: &str, vnt: &Vnt) -> bool {
if cmd.is_empty() {
return false;
}
match cmd.to_lowercase().trim() {
let cmd = cmd.to_lowercase();
let cmd = cmd.trim();
match cmd {
"list" => {
let list = command_list(&vnt);
console_out::console_device_list(list);
@@ -37,12 +44,24 @@ pub fn command_str(cmd: &str, vnt: &Vnt) -> bool {
let list = command_list(&vnt);
console_out::console_device_list_all(list);
}
"chart_a" => {
let chart = command_chart_a(&vnt);
console_out::console_chart_a(chart);
}
"stop" => {
let _ = vnt.stop();
return false;
}
_ => {}
}
if let Some(ip) = cmd.strip_prefix("chart_b") {
let chart = if ip.is_empty() {
command_chart_b(&vnt, &vnt.current_device().virtual_gateway.to_string())
} else {
command_chart_b(&vnt, &ip[1..])
};
console_out::console_chart_b(chart);
}
println!();
return true;
}
@@ -72,6 +91,14 @@ fn command_(cmd: CommandEnum) -> io::Result<()> {
let info = command_client.info()?;
console_out::console_info(info);
}
CommandEnum::ChartA => {
let chart = command_client.chart_a()?;
console_out::console_chart_a(chart);
}
CommandEnum::ChartB(input) => {
let chart = command_client.chart_b(&input)?;
console_out::console_chart_b(chart);
}
CommandEnum::Stop => {
command_client.stop()?;
}
@@ -81,6 +108,7 @@ fn command_(cmd: CommandEnum) -> io::Result<()> {
pub fn command_route(vnt: &Vnt) -> Vec<RouteItem> {
let route_table = vnt.route_table();
let server_addr = vnt.config().server_address_str.clone();
let mut route_list = Vec::with_capacity(route_table.len());
for (destination, routes) in route_table {
for route in routes {
@@ -93,11 +121,14 @@ pub fn command_route(vnt: &Vnt) -> Vec<RouteItem> {
} else {
route.rt.to_string()
};
let interface = if route.is_tcp {
format!("tcp@{}", route.addr)
} else {
route.addr.to_string()
let interface = match route.protocol {
ConnectProtocol::UDP => route.addr.to_string(),
ConnectProtocol::TCP => {
format!("tcp@{}", route.addr)
}
ConnectProtocol::WS | ConnectProtocol::WSS => server_addr.clone(),
};
let item = RouteItem {
destination: destination.to_string(),
next_hop,
@@ -145,7 +176,7 @@ pub fn command_list(vnt: &Vnt) -> Vec<DeviceItem> {
};
let (nat_traversal_type, rt) = if let Some(route) = vnt.route(&peer.virtual_ip) {
let nat_traversal_type = if route.metric == 1 {
if route.is_tcp {
if route.protocol.is_base_tcp() {
"tcp-p2p"
} else {
"p2p"
@@ -188,6 +219,7 @@ pub fn command_list(vnt: &Vnt) -> Vec<DeviceItem> {
client_secret_hash: peer.client_secret_hash,
current_client_secret,
current_client_secret_hash: client_encrypt_hash.to_vec(),
wire_guard: peer.wireguard,
};
list.push(item);
}
@@ -195,6 +227,7 @@ pub fn command_list(vnt: &Vnt) -> Vec<DeviceItem> {
}
pub fn command_info(vnt: &Vnt) -> Info {
let config = vnt.config();
let current_device = vnt.current_device();
let nat_info = vnt.nat_info();
let name = vnt.name().to_string();
@@ -202,7 +235,11 @@ pub fn command_info(vnt: &Vnt) -> Info {
let virtual_gateway = current_device.virtual_gateway().to_string();
let virtual_netmask = current_device.virtual_netmask.to_string();
let connect_status = format!("{:?}", vnt.connection_status());
let relay_server = current_device.connect_server.to_string();
let relay_server = if current_device.connect_server.port() == 0 {
config.server_address_str.clone()
} else {
current_device.connect_server.to_string()
};
let nat_type = format!("{:?}", nat_info.nat_type);
let public_ips: Vec<String> = nat_info.public_ips.iter().map(|v| v.to_string()).collect();
let public_ips = public_ips.join(",");
@@ -214,14 +251,18 @@ pub fn command_info(vnt: &Vnt) -> Info {
.ipv6()
.map(|v| v.to_string())
.unwrap_or("None".to_string());
let up = vnt.up_stream();
let down = vnt.down_stream();
#[cfg(feature = "port_mapping")]
let port_mapping_list = vnt.config().port_mapping_list.clone();
#[cfg(not(feature = "port_mapping"))]
let port_mapping_list = vec![];
let in_ips = vnt.config().in_ips.clone();
let out_ips = vnt.config().out_ips.clone();
let udp_listen_addr = nat_info
.udp_ports
.iter()
.map(|port| format!("0.0.0.0:{}", port))
.collect();
let tcp_listen_addr = format!("0.0.0.0:{}", nat_info.tcp_port);
Info {
name,
virtual_ip,
@@ -233,10 +274,80 @@ pub fn command_info(vnt: &Vnt) -> Info {
public_ips,
local_addr,
ipv6_addr,
up,
down,
port_mapping_list,
in_ips,
out_ips,
udp_listen_addr,
tcp_listen_addr,
}
}
pub fn command_chart_a(vnt: &Vnt) -> ChartA {
let disable_stats = !vnt.config().enable_traffic;
if disable_stats {
let mut chart = ChartA::default();
chart.disable_stats = true;
return chart;
}
let (up_total, up_map) = vnt.up_stream_all().unwrap_or_default();
let (down_total, down_map) = vnt.down_stream_all().unwrap_or_default();
ChartA {
disable_stats,
up_total,
down_total,
up_map,
down_map,
}
}
pub fn command_chart_b(vnt: &Vnt, input_str: &str) -> ChartB {
let disable_stats = !vnt.config().enable_traffic;
if disable_stats {
let mut chart = ChartB::default();
chart.disable_stats = true;
return chart;
}
let (_, up_map) = vnt.up_stream_history().unwrap_or_default();
let (_, down_map) = vnt.down_stream_history().unwrap_or_default();
let up_keys: HashSet<_> = up_map.keys().cloned().collect();
let down_keys: HashSet<_> = down_map.keys().cloned().collect();
let mut keys: Vec<Ipv4Addr> = up_keys.union(&down_keys).cloned().collect();
keys.sort();
if let Some(ip) = find_matching_ipv4_address(input_str, &keys) {
let (up_total, up_list) = up_map.get(&ip).cloned().unwrap_or_default();
let (down_total, down_list) = down_map.get(&ip).cloned().unwrap_or_default();
ChartB {
disable_stats,
ip: Some(ip),
up_total,
up_list,
down_total,
down_list,
}
} else {
ChartB::default()
}
}
fn match_from_end(input_str: &str, ip: &str) -> bool {
let mut input_chars = input_str.chars().rev();
let mut ip_chars = ip.chars().rev();
while let (Some(ic), Some(pc)) = (input_chars.next(), ip_chars.next()) {
if ic != pc {
return false;
}
}
input_chars.next().is_none() // Ensure all input characters matched
}
fn find_matching_ipv4_address(input_str: &str, ip_addresses: &[Ipv4Addr]) -> Option<Ipv4Addr> {
for &ip in ip_addresses {
let ip_str = ip.to_string();
if match_from_end(input_str, &ip_str) {
return Some(ip);
}
}
None
}
+16 -4
View File
@@ -1,3 +1,4 @@
use crate::command::command_chart_b;
use std::io;
use std::io::Write;
use std::net::UdpSocket;
@@ -62,15 +63,26 @@ fn command(cmd: &str, vnt: &Vnt) -> io::Result<String> {
.unwrap_or_else(|e| format!("error {:?}", e)),
"info" => serde_yaml::to_string(&crate::command::command_info(vnt))
.unwrap_or_else(|e| format!("error {:?}", e)),
"chart_a" => serde_yaml::to_string(&crate::command::command_chart_a(vnt))
.unwrap_or_else(|e| format!("error {:?}", e)),
"stop" => {
vnt.stop();
"stopped".to_string()
}
_ => {
format!(
"command '{}' not found. Try to enter: 'route'/'list'/'stop' \n",
cmd
)
if let Some(ip) = cmd.strip_prefix("chart_b") {
let chart = if ip.is_empty() {
command_chart_b(&vnt, &vnt.current_device().virtual_gateway.to_string())
} else {
command_chart_b(&vnt, &ip[1..])
};
serde_yaml::to_string(&chart).unwrap_or_else(|e| format!("error {:?}", e))
} else {
format!(
"command '{}' not found. Try to enter: 'route'/'list'/'stop' \n",
cmd
)
}
}
};
Ok(out_str)
+22 -13
View File
@@ -2,8 +2,8 @@ use anyhow::anyhow;
use std::net::Ipv4Addr;
use std::str::FromStr;
use crate::args_parse;
use crate::config::get_device_id;
use crate::{args_parse, config};
use serde::{Deserialize, Serialize};
use vnt::channel::punch::PunchModel;
use vnt::channel::UseChannelType;
@@ -45,10 +45,18 @@ pub struct FileConfig {
pub mapping: Vec<String>,
pub compressor: Option<String>,
pub vnt_mapping: Vec<String>,
pub disable_stats: bool,
// 允许传递wg流量
pub allow_wire_guard: bool,
pub local_dev: Option<String>,
}
impl Default for FileConfig {
fn default() -> Self {
let mut stun_server = Vec::new();
for x in config::PUB_STUN {
stun_server.push(x.to_string());
}
Self {
#[cfg(target_os = "windows")]
tap: false,
@@ -59,11 +67,7 @@ impl Default for FileConfig {
.unwrap_or("UnknownName")
.to_string(),
server_address: "nat1.wherewego.top:29872".to_string(),
stun_server: vec![
"stun1.l.google.com:19302".to_string(),
"stun2.l.google.com:19302".to_string(),
"stun.miwifi.com:3478".to_string(),
],
stun_server,
dns: vec![],
in_ips: vec![],
out_ips: vec![],
@@ -88,6 +92,9 @@ impl Default for FileConfig {
mapping: vec![],
compressor: None,
vnt_mapping: vec![],
disable_stats: false,
allow_wire_guard: false,
local_dev: None,
}
}
}
@@ -97,8 +104,8 @@ pub fn read_config(file_path: &str) -> anyhow::Result<(Config, Vec<String>, bool
let file_conf = match serde_yaml::from_str::<FileConfig>(&conf) {
Ok(val) => val,
Err(e) => {
log::error!("{:?}", e);
return Err(anyhow!("{}", e));
log::error!("serde_yaml::from_str {:?}", e);
return Err(anyhow!("serde_yaml::from_str {:?}", e));
}
};
if file_conf.token.is_empty() {
@@ -121,12 +128,12 @@ pub fn read_config(file_path: &str) -> anyhow::Result<(Config, Vec<String>, bool
None => None,
Some(r) => Some(r.map_err(|e| anyhow!("ip {:?} error:{}", &file_conf.ip, e))?),
};
let cipher_model = {
let cipher_model = if let Some(v) = file_conf.cipher_model {
CipherModel::from_str(&v).map_err(|e| anyhow!("{}", e))?
} else {
#[cfg(not(any(feature = "aes_gcm", feature = "server_encrypt")))]
if file_conf.password.is_some() && file_conf.cipher_model.is_none() {
if file_conf.password.is_some() {
Err(anyhow!("cipher_model undefined"))?
} else if let Some(v) = file_conf.cipher_model {
CipherModel::from_str(&v).map_err(|e| anyhow!("{}", e))?
} else {
CipherModel::None
}
@@ -156,7 +163,6 @@ pub fn read_config(file_path: &str) -> anyhow::Result<(Config, Vec<String>, bool
out_ips,
file_conf.password,
file_conf.mtu,
file_conf.tcp,
virtual_ip,
#[cfg(feature = "integrated_tun")]
#[cfg(feature = "ip_proxy")]
@@ -175,6 +181,9 @@ pub fn read_config(file_path: &str) -> anyhow::Result<(Config, Vec<String>, bool
#[cfg(feature = "port_mapping")]
file_conf.mapping,
compressor,
!file_conf.disable_stats,
file_conf.allow_wire_guard,
file_conf.local_dev,
)?;
Ok((config, file_conf.vnt_mapping, file_conf.cmd))
+6
View File
@@ -1,3 +1,9 @@
pub const PUB_STUN: [&'static str; 4] = [
"stun.miwifi.com",
"stun.chat.bilibili.com",
"stun.hitv.com",
"stun.cdnbye.com",
];
#[cfg(feature = "file_config")]
mod file_config;
+138 -11
View File
@@ -1,7 +1,8 @@
use console::{style, Style};
use std::collections::HashSet;
use std::net::Ipv4Addr;
use crate::command::entity::{DeviceItem, Info, RouteItem};
use crate::command::entity::{ChartA, ChartB, DeviceItem, Info, RouteItem};
pub mod table;
@@ -21,11 +22,14 @@ pub fn console_info(status: Info) {
println!("NAT type: {}", style(status.nat_type).green());
println!("Relay server: {}", style(status.relay_server).green());
println!(
"Udp listen: {}",
style(status.udp_listen_addr.join(", ")).green()
);
println!("Tcp listen: {}", style(status.tcp_listen_addr).green());
println!("Public ips: {}", style(status.public_ips).green());
println!("Local addr: {}", style(status.local_addr).green());
println!("IPv6: {}", style(status.ipv6_addr).green());
println!("Up: {}", style(convert(status.up)).green());
println!("Down: {}", style(convert(status.down)).green());
if !status.port_mapping_list.is_empty() {
println!("------------------------------------------");
@@ -128,15 +132,21 @@ pub fn console_device_list(mut list: Vec<DeviceItem>) {
("Rt".to_string(), Style::new()),
]);
for item in list {
let name = if item.wire_guard {
format!("{}(wg)", item.name)
} else {
item.name
};
if &item.status == "Online" {
if item.client_secret != item.current_client_secret
|| (!item.current_client_secret_hash.is_empty()
&& !item.client_secret_hash.is_empty()
&& item.current_client_secret_hash != item.client_secret_hash)
if !item.wire_guard
&& (item.client_secret != item.current_client_secret
|| (!item.current_client_secret_hash.is_empty()
&& !item.client_secret_hash.is_empty()
&& item.current_client_secret_hash != item.client_secret_hash))
{
//加密状态不一致,无法通信的
out_list.push(vec![
(item.name, Style::new().red()),
(name, Style::new().red()),
(item.virtual_ip, Style::new().red()),
(item.status, Style::new().red()),
("Mismatch".to_string(), Style::new().red()),
@@ -145,7 +155,7 @@ pub fn console_device_list(mut list: Vec<DeviceItem>) {
} else {
if item.nat_traversal_type.contains("p2p") {
out_list.push(vec![
(item.name, Style::new().green()),
(name, Style::new().green()),
(item.virtual_ip, Style::new().green()),
(item.status, Style::new().green()),
(item.nat_traversal_type, Style::new().green()),
@@ -153,7 +163,7 @@ pub fn console_device_list(mut list: Vec<DeviceItem>) {
]);
} else {
out_list.push(vec![
(item.name, Style::new().yellow()),
(name, Style::new().yellow()),
(item.virtual_ip, Style::new().yellow()),
(item.status, Style::new().yellow()),
(item.nat_traversal_type, Style::new().yellow()),
@@ -163,7 +173,7 @@ pub fn console_device_list(mut list: Vec<DeviceItem>) {
}
} else {
out_list.push(vec![
(item.name, Style::new().color256(102)),
(name, Style::new().color256(102)),
(item.virtual_ip, Style::new().color256(102)),
(item.status, Style::new().color256(102)),
("".to_string(), Style::new().color256(102)),
@@ -237,3 +247,120 @@ pub fn console_device_list_all(mut list: Vec<DeviceItem>) {
}
table::println_table(out_list)
}
pub fn console_chart_a(chart_a: ChartA) {
if chart_a.disable_stats {
println!("Traffic statistics not enabled");
return;
}
println!();
println!("-----------------------------------------------------------------");
println!(
"Upload total = {}",
style(convert(chart_a.up_total)).green()
);
println!(
"Download total = {}",
style(convert(chart_a.down_total)).green()
);
println!("-----------------------------------------------------------------");
let up_keys: HashSet<_> = chart_a.up_map.keys().cloned().collect();
let down_keys: HashSet<_> = chart_a.down_map.keys().cloned().collect();
let mut keys: Vec<Ipv4Addr> = up_keys.union(&down_keys).cloned().collect();
// 排序
keys.sort();
// 找到最大的值,用于缩放条形图长度
let up_max_value = *chart_a.up_map.values().max().unwrap_or(&0);
let down_max_value = *chart_a.down_map.values().max().unwrap_or(&0);
let max_value = up_max_value.max(down_max_value);
let max_value = max_value.max(1);
let max_height = 50;
// 打印条形图
for key in &keys {
if let Some(&value) = chart_a.up_map.get(key) {
let bar = "".repeat(((value as f64 / max_value as f64) * max_height as f64) as usize);
println!(
"{:<10} | {} upload {}",
key,
bar,
style(convert(value)).green()
);
}
if let Some(&value) = chart_a.down_map.get(key) {
let bar = "".repeat(((value as f64 / max_value as f64) * max_height as f64) as usize);
println!(
"{:<10} | {} download {}",
key,
bar,
style(convert(value)).green()
);
}
println!("-");
}
}
pub fn console_chart_b(chart_b: ChartB) {
if chart_b.disable_stats {
println!("Traffic statistics not enabled");
return;
}
let ip = if let Some(ip) = chart_b.ip {
ip
} else {
println!("Ip: None");
return;
};
println!("---------------------------- upload ----------------------------");
println!("IP: {}", ip);
println!("Upload total: {}", style(convert(chart_b.up_total)).green());
println!(
"Max: {}",
style(convert(
chart_b
.up_list
.iter()
.max()
.cloned()
.map_or(0, |v| v as u64)
))
.green()
);
console_chart_b_list(chart_b.up_list);
println!("---------------------------- download ----------------------------");
println!("IP: {}", ip);
println!(
"Download total: {}",
style(convert(chart_b.down_total)).green()
);
println!(
"Max: {}",
style(convert(
chart_b
.down_list
.iter()
.max()
.cloned()
.map_or(0, |v| v as u64)
))
.green()
);
console_chart_b_list(chart_b.down_list);
}
fn console_chart_b_list(list: Vec<usize>) {
let max_value = *list.iter().max().unwrap_or(&0);
let max_value = max_value.max(1);
let max_height = max_value.min(20);
// 遍历从最大高度到0
for i in (0..=max_height).rev() {
for &value in &list {
let scaled_value = (value as f64 / max_value as f64 * max_height as f64) as usize;
if scaled_value >= i {
print!("");
} else {
print!(" ");
}
}
println!();
}
}
+14 -18
View File
@@ -52,6 +52,19 @@ pub fn get_unique_identifier() -> Option<String> {
pub fn get_unique_identifier() -> Option<String> {
use std::process::Command;
// Try to execute 'dmidecode' command to get the system identifier first.
if let Ok(output) = Command::new("dmidecode")
.arg("-s")
.arg("system-uuid")
.output()
{
let identifier = String::from_utf8_lossy(&output.stdout).trim().to_owned();
if !identifier.is_empty() {
return Some(identifier.to_string());
}
}
// Try to read file /etc/machine-id if 'dmidecode' command cannot be executed or get nothing.
// 对 linux 或 wsl 来说,读取 /etc/machine-id 即可获取当前操作系统的
// 唯一标识,而且某些环境没有预装`dmidecode`命令
if let Ok(identifier) = std::fs::read_to_string("/etc/machine-id") {
@@ -61,22 +74,5 @@ pub fn get_unique_identifier() -> Option<String> {
}
}
let output = match Command::new("dmidecode")
.arg("-s")
.arg("system-uuid")
.output()
{
Ok(output) => output,
Err(_) => {
return None;
}
};
let result = String::from_utf8_lossy(&output.stdout);
let identifier = result.trim();
if identifier.is_empty() {
None
} else {
Some(identifier.to_string())
}
None
}
+18 -14
View File
@@ -1,6 +1,6 @@
[package]
name = "vn-link-cli"
version = "1.2.10"
version = "1.2.14"
edition = "2021"
[dependencies]
@@ -11,20 +11,24 @@ log = "0.4.17"
[features]
default = ["default-feature"]
openssl = ["vn-link/openssl","common/openssl"]
openssl-vendored = ["vn-link/openssl-vendored","common/openssl-vendored"]
ring-cipher = ["vn-link/ring-cipher","common/ring-cipher"]
aes_cbc = ["vn-link/aes_cbc","common/aes_cbc"]
aes_ecb = ["vn-link/aes_ecb","common/aes_ecb"]
sm4_cbc = ["vn-link/sm4_cbc","common/sm4_cbc"]
aes_gcm = ["vn-link/aes_gcm","common/aes_gcm"]
chacha20_poly1305 = ["vn-link/chacha20_poly1305","common/chacha20_poly1305"]
server_encrypt = ["vn-link/server_encrypt","common/server_encrypt"]
port_mapping = ["vn-link/port_mapping","common/port_mapping"]
lz4 = ["vn-link/lz4_compress","common/lz4"]
zstd = ["vn-link/zstd_compress","common/zstd"]
default-feature = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "port_mapping", "log", "command", "file_config", "lz4", "ws"]
openssl = ["vn-link/openssl", "common/openssl"]
openssl-vendored = ["vn-link/openssl-vendored", "common/openssl-vendored"]
ring-cipher = ["vn-link/ring-cipher", "common/ring-cipher"]
aes_cbc = ["vn-link/aes_cbc", "common/aes_cbc"]
aes_ecb = ["vn-link/aes_ecb", "common/aes_ecb"]
sm4_cbc = ["vn-link/sm4_cbc", "common/sm4_cbc"]
aes_gcm = ["vn-link/aes_gcm", "common/aes_gcm"]
chacha20_poly1305 = ["vn-link/chacha20_poly1305", "common/chacha20_poly1305"]
server_encrypt = ["vn-link/server_encrypt", "common/server_encrypt"]
port_mapping = ["vn-link/port_mapping", "common/port_mapping"]
lz4 = ["vn-link/lz4_compress", "common/lz4"]
zstd = ["vn-link/zstd_compress", "common/zstd"]
upnp = ["vn-link/upnp", "common/upnp"]
ws = ["vn-link/ws", "common/ws"]
wss = ["vn-link/wss", "common/wss"]
log = ["common/log"]
command = ["common/command"]
file_config = ["common/file_config"]
default-feature = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "port_mapping", "log", "command", "file_config", "lz4"]
+7 -2
View File
@@ -12,7 +12,12 @@ fn main() {
}
}
Err(e) => {
println!("{}", e);
log::error!(
"parse error={:?} cmd={:?}",
e,
std::env::args().collect::<Vec<String>>()
);
println!("Error {:?}", e);
return;
}
};
@@ -65,7 +70,7 @@ async fn main0(config: Config, vn_link_config: VnLinkConfig, _show_cmd: bool) {
let mut reader = tokio::io::BufReader::new(tokio::io::stdin());
loop {
cmd.clear();
println!("======== input:list,info,route,all,stop ========");
println!("======== input:list,info,route,all,stop,chart_a,chart_b[:ip] ========");
match reader.read_line(&mut cmd).await {
Ok(len) => {
if !common::command::command_str(&cmd[..len], vnt_c) {
+5 -2
View File
@@ -1,10 +1,10 @@
[package]
name = "vn-link"
version = "1.2.10"
version = "1.2.14"
edition = "2021"
[dependencies]
lwip-rs = { git = "https://github.com/lbl8603/lwip-rs" }
lwip-rs = { git = "https://github.com/vnt-dev/lwip-rs" }
vnt = { path = "../vnt", package = "vnt", default-features = false }
log = "0.4.17"
anyhow = "1.0.82"
@@ -27,3 +27,6 @@ server_encrypt = ["vnt/server_encrypt"]
port_mapping = ["vnt/port_mapping"]
lz4_compress = ["vnt/lz4_compress"]
zstd_compress = ["vnt/zstd_compress"]
upnp = ["vnt/upnp"]
ws = ["vnt/ws"]
wss = ["vnt/wss"]
+6 -5
View File
@@ -1,6 +1,6 @@
[package]
name = "vnt-cli"
version = "1.2.10"
version = "1.2.14"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -10,7 +10,7 @@ vnt = { path = "../vnt", package = "vnt", default-features = false, features = [
common = { path = "../common", default-features = false, features = ["integrated_tun"] }
log = "0.4.17"
anyhow = "1.0.82"
console = "0.15.2"
[target.'cfg(any(target_os = "linux",target_os = "macos"))'.dependencies]
sudo = "0.6.0"
@@ -21,7 +21,7 @@ winapi = { version = "0.3.9", features = ["handleapi", "processthreadsapi", "win
[features]
default = ["default-feature"]
default-feature = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "ip_proxy", "port_mapping", "log", "command", "file_config", "lz4"]
default-feature = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "ip_proxy", "port_mapping", "log", "command", "file_config", "lz4", "ws"]
openssl = ["vnt/openssl", "common/openssl"]
openssl-vendored = ["vnt/openssl-vendored", "common/openssl-vendored"]
@@ -36,11 +36,12 @@ port_mapping = ["vnt/port_mapping", "common/port_mapping"]
lz4 = ["vnt/lz4_compress", "common/lz4"]
zstd = ["vnt/zstd_compress", "common/zstd"]
ip_proxy = ["vnt/ip_proxy", "common/ip_proxy"]
upnp = ["vnt/upnp", "common/upnp"]
ws = ["vnt/ws", "common/ws"]
wss = ["vnt/wss", "common/wss"]
log = ["common/log"]
command = ["common/command"]
file_config = ["common/file_config"]
[build-dependencies]
rand = "0.8.5"
chrono = "0.4.23"
+15 -3
View File
@@ -74,9 +74,11 @@
设置虚拟网卡的mtu值,大多数情况下使用默认值效率会更高,也可根据实际情况微调这个值,不加密默认为1450,加密默认为1410
### --tcp
### ~~--tcp~~
和服务端使用tcp通信。有些网络提供商对UDP限制比较大,这个时候可以选择使用TCP模式,提高稳定性。一般来说udp延迟和消耗更低
~~和服务端使用tcp通信。有些网络提供商对UDP限制比较大,这个时候可以选择使用TCP模式,提高稳定性。一般来说udp延迟和消耗更低~~
新版本使用 `-s tcp://`的形式使用tcp
### --ip `<IP>`
@@ -135,7 +137,7 @@ aes_gcm/aes_cbc/aes_ecb/sm4_cbc/chacha20_poly1305/chacha20/xor,默认使用aes
### --no-proxy
关闭内置的ip代理,内置的代理较为简单,而且一般来说直接使用网卡NAT转发性能会更高,
有需要可以自行配置NAT转发,[可参考‘编译’小节中的NAT配置](https://github.com/lbl8603/vnt#%E7%BC%96%E8%AF%91)
有需要可以自行配置NAT转发,[可参考‘编译’小节中的NAT配置](https://github.com/vnt-dev/vnt#%E7%BC%96%E8%AF%91)
### --dns `<223.5.5.5>`
@@ -201,6 +203,8 @@ mapping:
- udp:0.0.0.0:80-10.26.0.10:80 # 映射udp数据
- tcp:0.0.0.0:80-10.26.0.10:81 # 映射tcp数据
- tcp:0.0.0.0:82-localhost:83 # 映射tcp数据
disable_stats: false # 为true表示关闭统计
allow_wire_guard: false # 为true则表示允许接入wg
```
或者需要哪个配置就加哪个,当然token是必须的
@@ -223,6 +227,14 @@ token: xxx #组网token
模拟延迟,整数,单位毫秒(ms),程序会按设定的值延迟发包,可用于模拟弱网
### --disable-stats
关闭流量统计
### --allow-wg
允许接入WireGuard客户端,和wg混用时必须开启此参数
### --list
在后台运行时,查看其他设备列表
+9 -2
View File
@@ -1,4 +1,5 @@
use common::callback;
use console::style;
use vnt::core::{Config, Vnt};
mod root_check;
fn main() {
@@ -11,7 +12,12 @@ fn main() {
}
}
Err(e) => {
println!("{}", e);
log::error!(
"parse error={:?} cmd={:?}",
e,
std::env::args().collect::<Vec<String>>()
);
println!("{}", style(format!("Error {:?}", e)).red());
return;
}
};
@@ -35,6 +41,7 @@ fn main0(config: Config, _show_cmd: bool) {
let vnt_util = match Vnt::new(config, callback::VntHandler {}) {
Ok(vnt) => vnt,
Err(e) => {
log::error!("vnt create error {:?}", e);
println!("error: {:?}", e);
std::process::exit(1);
}
@@ -77,7 +84,7 @@ fn main0(config: Config, _show_cmd: bool) {
let mut cmd = String::new();
loop {
cmd.clear();
println!("======== input:list,info,route,all,stop ========");
println!("======== input:list,info,route,all,stop,chart_a,chart_b[:ip] ========");
match std::io::stdin().read_line(&mut cmd) {
Ok(len) => {
if !common::command::command_str(&cmd[..len], &vnt_util) {
+29 -13
View File
@@ -1,12 +1,12 @@
[package]
name = "vnt"
version = "1.2.10"
version = "1.2.14"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
tun = { path = "tun" ,optional = true}
tun = { path = "tun", optional = true }
packet = { path = "./packet" }
bytes = "1.5.0"
log = "0.4.17"
@@ -17,8 +17,8 @@ parking_lot = "0.12.1"
rand = "0.8.5"
sha2 = { version = "0.10.6", features = ["oid"] }
thiserror = "1.0.37"
protobuf = "3.2.0"
socket2 = { version = "0.5.2", features = ["all"] }
protobuf = "=3.2.0"
socket2 = { version = "0.5.7", features = ["all"] }
aes-gcm = { version = "0.10.2", optional = true }
ring = { version = "0.17.0", optional = true }
cbc = { version = "0.1.2", optional = true }
@@ -29,31 +29,44 @@ aes = "0.8.3"
stun-format = { version = "1.0.1", features = ["fmt", "rfc3489"] }
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 }
openssl-sys = { git = "https://github.com/vnt-dev/rust-openssl", optional = true }
libsm = { git = "https://github.com/vnt-dev/libsm", optional = true }
mio = { version = "0.8.10", features = ["os-poll", "net", "os-ext"] }
mio = { version = "=0.8.11", features = ["os-poll", "net", "os-ext"] }
crossbeam-queue = "0.3.11"
anyhow = "1.0.82"
dns-parser = "0.8.0"
tokio = { version = "1.37.0", features = ["full"], optional = true }
tokio = { version = "1.37.0", features = ["full"] }
lz4_flex = { version = "0.11", default-features = false, optional = true }
zstd = { version = "0.13.1", optional = true }
fnv = "1.0.7"
igd = { version = "0.12.1", optional = true }
tokio-tungstenite = { version = "0.23.1", optional = true }
rustls = { version = "0.23.0", features = ["ring"], default-features = false, optional = true }
network-interface = "2.0.0"
futures-util = "0.3.30"
[target.'cfg(target_os = "windows")'.dependencies]
libloading = "0.8.0"
windows-sys = {version = "0.59.0",features = [ "Win32_Foundation",
"Win32_NetworkManagement",
"Win32_NetworkManagement_IpHelper",
"Win32_Networking_WinSock",
"Win32_System_IO",
"Win32_System_Threading",
"Win32_System_WindowsProgramming",]}
[build-dependencies]
protobuf-codegen = "3.2.0"
protobuf-codegen = "=3.2.0"
protoc-bin-vendored = "3.0.0"
cfg_aliases = "0.2.1"
[features]
default = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "ip_proxy", "port_mapping", "lz4_compress", "zstd_compress","integrated_tun"]
default = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "ip_proxy", "port_mapping", "lz4_compress", "zstd_compress", "integrated_tun"]
openssl = ["openssl-sys"]
# 从源码编译
openssl-vendored = ["openssl-sys/vendored"]
@@ -64,8 +77,11 @@ sm4_cbc = ["libsm"]
aes_gcm = ["aes-gcm"]
chacha20_poly1305 = ["chacha20poly1305", "chacha20"]
server_encrypt = ["aes-gcm", "rsa", "spki"]
ip_proxy = ["tokio"]
port_mapping = ["tokio"]
ip_proxy = []
port_mapping = []
lz4_compress = ["lz4_flex"]
zstd_compress = ["zstd"]
integrated_tun = ["tun"]
upnp = ["igd"]
ws = ["tokio-tungstenite"]
wss = ["ws", "tokio-tungstenite/rustls-tls-native-roots", "tokio-tungstenite/rustls-tls-webpki-roots", "rustls"]
+4 -7
View File
@@ -71,14 +71,12 @@ unsigned short getChecksum(unsigned short * iphead, int count)
pub fn cal_checksum(buffer: &[u8]) -> u16 {
use std::io::Cursor;
let mut sum = 0;
let length = buffer.len();
let mut buffer = Cursor::new(buffer);
while let Ok(value) = buffer.read_u16::<BigEndian>() {
sum += u32::from(value);
}
if length & 1 == 1 {
//奇数,说明还有一位,不足的补0
sum += u32c(buffer.read_u8().unwrap(), 0);
if let Ok(l) = buffer.read_u8() {
sum += u32c(l, 0);
}
while sum >> 16 != 0 {
sum = (sum & 0xffff) + (sum >> 16);
@@ -119,9 +117,8 @@ pub fn ipv4_cal_checksum(
while let Ok(value) = buffer.read_u16::<BigEndian>() {
sum += u32::from(value);
}
if length & 1 == 1 {
//奇数,说明还有一位
sum += u32c(buffer.read_u8().unwrap(), 0);
if let Ok(l) = buffer.read_u8() {
sum += u32c(l, 0);
}
while sum >> 16 != 0 {
sum = (sum & 0xffff) + (sum >> 16);
+13
View File
@@ -43,6 +43,7 @@ message DeviceInfo {
uint32 device_status = 3;
bool client_secret = 4;
bytes client_secret_hash = 5;
bool wireguard = 6;
}
message DeviceList {
@@ -63,11 +64,23 @@ message PunchInfo {
uint32 tcp_port = 11;
repeated uint32 udp_ports = 12;
repeated uint32 public_ports = 13;
uint32 public_tcp_port = 14;
PunchNatModel punch_model = 15;
}
enum PunchNatType {
Symmetric = 0;
Cone = 1;
}
enum PunchNatModel {
All = 0;
IPv4 = 1;
IPv6 = 2;
IPv4Tcp = 3;
IPv4Udp = 4;
IPv6Tcp = 5;
IPv6Udp = 6;
}
/// 向服务器上报客户端状态信息
message ClientStatusInfo {
fixed32 source = 1;
+146 -116
View File
@@ -1,7 +1,7 @@
use fnv::FnvHashMap;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV6, UdpSocket};
use std::net::{Ipv4Addr, SocketAddr, UdpSocket};
use std::ops::Deref;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
use std::time::{Duration, Instant};
use std::{io, thread};
@@ -12,7 +12,10 @@ use rand::Rng;
use crate::channel::punch::NatType;
use crate::channel::sender::{AcceptSocketSender, PacketSender};
use crate::channel::{Route, RouteKey, UseChannelType, DEFAULT_RT};
use crate::channel::socket::LocalInterface;
use crate::channel::{ConnectProtocol, Route, RouteKey, UseChannelType, DEFAULT_RT};
use crate::protocol::NetPacket;
use crate::util::limit::TrafficMeterMultiAddress;
/// 传输通道上下文,持有udp socket、tcp socket和路由信息
#[derive(Clone)]
@@ -23,14 +26,17 @@ pub struct ChannelContext {
impl ChannelContext {
pub fn new(
main_udp_socket: Vec<UdpSocket>,
v4_len: usize,
use_channel_type: UseChannelType,
first_latency: bool,
is_tcp: bool,
protocol: ConnectProtocol,
packet_loss_rate: Option<f64>,
packet_delay: u32,
use_ipv6: bool,
up_traffic_meter: Option<TrafficMeterMultiAddress>,
down_traffic_meter: Option<TrafficMeterMultiAddress>,
default_interface: LocalInterface,
) -> Self {
let channel_num = main_udp_socket.len();
let channel_num = v4_len;
assert_ne!(channel_num, 0, "not channel");
let packet_loss_rate = packet_loss_rate
.map(|v| {
@@ -44,14 +50,17 @@ impl ChannelContext {
.unwrap_or(0);
let inner = ContextInner {
main_udp_socket,
v4_len,
sub_udp_socket: RwLock::new(Vec::new()),
tcp_map: RwLock::new(FnvHashMap::default()),
packet_map: RwLock::new(FnvHashMap::default()),
route_table: RouteTable::new(use_channel_type, first_latency, channel_num),
is_tcp,
protocol,
packet_loss_rate,
packet_delay,
main_index: AtomicUsize::new(0),
use_ipv6,
up_traffic_meter,
down_traffic_meter,
default_interface,
default_route_key: AtomicCell::default(),
};
Self {
inner: Arc::new(inner),
@@ -68,41 +77,50 @@ impl Deref for ChannelContext {
}
/// 对称网络增加的udp socket数目,有助于增加打洞成功率
pub const SYMMETRIC_CHANNEL_NUM: usize = 100;
pub const SYMMETRIC_CHANNEL_NUM: usize = 84;
const PACKET_LOSS_RATE_DENOMINATOR: u32 = 100_0000;
pub struct ContextInner {
// 核心udp socket
pub(crate) main_udp_socket: Vec<UdpSocket>,
v4_len: usize,
// 对称网络增加的udp socket
sub_udp_socket: RwLock<Vec<UdpSocket>>,
// tcp数据发送器
pub(crate) tcp_map: RwLock<FnvHashMap<SocketAddr, PacketSender>>,
pub(crate) packet_map: RwLock<FnvHashMap<RouteKey, PacketSender>>,
// 路由信息
pub route_table: RouteTable,
// 是否使用tcp连接服务器
is_tcp: bool,
// 使用什么协议连接服务器
protocol: ConnectProtocol,
//控制丢包率,取值v=[0,100_0000] 丢包率r=v/100_0000
packet_loss_rate: u32,
//控制延迟
packet_delay: u32,
main_index: AtomicUsize,
use_ipv6: bool,
pub(crate) up_traffic_meter: Option<TrafficMeterMultiAddress>,
pub(crate) down_traffic_meter: Option<TrafficMeterMultiAddress>,
default_interface: LocalInterface,
default_route_key: AtomicCell<Option<RouteKey>>,
}
impl ContextInner {
pub fn use_channel_type(&self) -> UseChannelType {
self.route_table.use_channel_type
}
pub fn default_interface(&self) -> &LocalInterface {
&self.default_interface
}
pub fn set_default_route_key(&self, route_key: RouteKey) {
self.default_route_key.store(Some(route_key));
}
/// 通过sub_udp_socket是否为空来判断是否为锥形网络
pub fn is_cone(&self) -> bool {
self.sub_udp_socket.read().is_empty()
}
pub fn is_main_tcp(&self) -> bool {
self.is_tcp
pub fn main_protocol(&self) -> ConnectProtocol {
self.protocol
}
pub fn is_udp_main(&self, route_key: &RouteKey) -> bool {
!route_key.is_tcp() && route_key.index < self.main_udp_socket.len()
route_key.protocol().is_udp() && route_key.index < self.main_udp_socket.len()
}
pub fn first_latency(&self) -> bool {
self.route_table.first_latency
@@ -112,7 +130,7 @@ impl ContextInner {
&self,
nat_type: NatType,
udp_socket_sender: &AcceptSocketSender<Option<Vec<mio::net::UdpSocket>>>,
) -> io::Result<()> {
) -> anyhow::Result<()> {
let mut write_guard = self.sub_udp_socket.write();
match nat_type {
NatType::Symmetric => {
@@ -121,9 +139,11 @@ impl ContextInner {
}
let mut vec = Vec::with_capacity(SYMMETRIC_CHANNEL_NUM);
for _ in 0..SYMMETRIC_CHANNEL_NUM {
let udp = UdpSocket::bind("0.0.0.0:0")?;
//副通道使用异步io
udp.set_nonblocking(true)?;
let udp = crate::channel::socket::bind_udp(
"0.0.0.0:0".parse().unwrap(),
&self.default_interface,
)?;
let udp: UdpSocket = udp.into();
vec.push(udp);
}
let mut mio_vec = Vec::with_capacity(SYMMETRIC_CHANNEL_NUM);
@@ -144,54 +164,68 @@ impl ContextInner {
}
Ok(())
}
#[inline]
pub fn channel_num(&self) -> usize {
self.v4_len
}
#[inline]
pub fn main_len(&self) -> usize {
self.main_udp_socket.len()
}
/// 获取核心udp监听的端口,用于其他客户端连接
pub fn main_local_udp_port(&self) -> io::Result<Vec<u16>> {
let mut ports = Vec::new();
for udp in self.main_udp_socket.iter() {
for udp in self.main_udp_socket[..self.v4_len].iter() {
ports.push(udp.local_addr()?.port())
}
Ok(ports)
}
pub fn send_tcp(&self, buf: &[u8], addr: SocketAddr) -> io::Result<()> {
if let Some(tcp) = self.tcp_map.read().get(&addr) {
pub fn send_tcp(&self, buf: &[u8], route_key: &RouteKey) -> io::Result<()> {
if let Some(tcp) = self.packet_map.read().get(route_key) {
tcp.try_send(buf)
} else {
Err(io::Error::from(io::ErrorKind::NotFound))
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("dest={:?}", route_key),
))
}
}
pub fn send_main_udp(&self, index: usize, buf: &[u8], mut addr: SocketAddr) -> io::Result<()> {
if self.use_ipv6 {
//如果是v4地址则需要转换成v6
if let SocketAddr::V4(ipv4) = addr {
addr = SocketAddr::V6(SocketAddrV6::new(
ipv4.ip().to_ipv6_mapped(),
ipv4.port(),
0,
0,
pub fn send_main_udp(&self, index: usize, buf: &[u8], addr: SocketAddr) -> io::Result<()> {
if let Some(udp) = self.main_udp_socket.get(index) {
udp.send_to(buf, addr)?;
Ok(())
} else {
Err(io::Error::new(io::ErrorKind::Other, "overflow"))
}
}
/// 将数据发送到默认通道,一般发往服务器才用此方法
pub fn send_default<B: AsRef<[u8]>>(
&self,
buf: &NetPacket<B>,
addr: SocketAddr,
) -> io::Result<()> {
if self.protocol.is_udp() {
if addr.is_ipv4() {
self.send_main_udp(0, buf.buffer(), addr)?
} else {
self.send_main_udp(self.v4_len, buf.buffer(), addr)?
}
} else {
if let Some(key) = self.default_route_key.load() {
self.send_tcp(buf.buffer(), &key)?
} else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("dest={:?}", addr),
));
}
}
self.main_udp_socket[index].send_to(buf, addr)?;
if let Some(up_traffic_meter) = &self.up_traffic_meter {
up_traffic_meter.add_traffic(buf.destination(), buf.data_len());
}
Ok(())
}
/// 将数据发送到默认通道,一般发往服务器才用此方法
pub fn send_default(&self, buf: &[u8], addr: SocketAddr) -> io::Result<()> {
if self.is_tcp {
//服务端地址只在重连时检测变化
self.send_tcp(buf, addr)
} else {
self.send_main_udp(self.main_index.load(Ordering::Relaxed), buf, addr)
}
}
pub fn change_main_index(&self) {
let index = (self.main_index.load(Ordering::Relaxed) + 1) % self.main_udp_socket.len();
self.main_index.store(index, Ordering::Relaxed);
}
/// 此方法仅用于对称网络打洞
pub fn try_send_all(&self, buf: &[u8], addr: SocketAddr) {
self.try_send_all_main(buf, addr);
@@ -199,7 +233,7 @@ impl ContextInner {
if let Err(e) = udp.send_to(buf, addr) {
log::warn!("{:?},add={:?}", e, addr);
}
thread::sleep(Duration::from_millis(1));
thread::sleep(Duration::from_millis(3));
}
}
pub fn try_send_all_main(&self, buf: &[u8], addr: SocketAddr) {
@@ -210,9 +244,9 @@ impl ContextInner {
}
}
/// 发送网络数据
pub fn send_ipv4_by_id(
pub fn send_ipv4_by_id<B: AsRef<[u8]>>(
&self,
buf: &[u8],
buf: &NetPacket<B>,
id: &Ipv4Addr,
server_addr: SocketAddr,
send_default: bool,
@@ -222,6 +256,7 @@ impl ContextInner {
return Ok(());
}
}
if self.packet_delay > 0 {
thread::sleep(Duration::from_millis(self.packet_delay as _));
}
@@ -238,7 +273,7 @@ impl ContextInner {
Ok(())
}
/// 将数据发到指定id
pub fn send_by_id(&self, buf: &[u8], id: &Ipv4Addr) -> io::Result<()> {
pub fn send_by_id<B: AsRef<[u8]>>(&self, buf: &NetPacket<B>, id: &Ipv4Addr) -> io::Result<()> {
let mut c = 0;
loop {
let route = self.route_table.get_route_by_id(c, id)?;
@@ -258,25 +293,35 @@ impl ContextInner {
}
}
/// 将数据发到指定路由
pub fn send_by_key(&self, buf: &[u8], route_key: RouteKey) -> io::Result<()> {
if route_key.is_tcp {
self.send_tcp(buf, route_key.addr)
} else {
if let Some(main_udp) = self.main_udp_socket.get(route_key.index) {
main_udp.send_to(buf, route_key.addr)?;
} else {
if let Some(udp) = self
.sub_udp_socket
.read()
.get(route_key.index - self.main_udp_socket.len())
{
udp.send_to(buf, route_key.addr)?;
pub fn send_by_key<B: AsRef<[u8]>>(
&self,
buf: &NetPacket<B>,
route_key: RouteKey,
) -> io::Result<()> {
match route_key.protocol() {
ConnectProtocol::UDP => {
if let Some(main_udp) = self.main_udp_socket.get(route_key.index) {
main_udp.send_to(buf.buffer(), route_key.addr)?;
} else {
Err(io::Error::from(io::ErrorKind::NotFound))?
if let Some(udp) = self
.sub_udp_socket
.read()
.get(route_key.index - self.main_len())
{
udp.send_to(buf.buffer(), route_key.addr)?;
} else {
Err(io::Error::from(io::ErrorKind::NotFound))?
}
}
}
Ok(())
ConnectProtocol::TCP | ConnectProtocol::WS | ConnectProtocol::WSS => {
self.send_tcp(buf.buffer(), &route_key)?
}
}
if let Some(up_traffic_meter) = &self.up_traffic_meter {
up_traffic_meter.add_traffic(buf.destination(), buf.data_len());
}
Ok(())
}
pub fn remove_route(&self, ip: &Ipv4Addr, route_key: RouteKey) {
self.route_table.remove_route(ip, route_key)
@@ -327,18 +372,18 @@ impl RouteTable {
}
Err(io::Error::new(io::ErrorKind::NotFound, "route not found"))
}
pub fn add_route_if_absent(&self, id: Ipv4Addr, route: Route) {
pub fn add_route_if_absent(&self, id: Ipv4Addr, route: Route) -> bool {
self.add_route_(id, route, true)
}
pub fn add_route(&self, id: Ipv4Addr, route: Route) {
pub fn add_route(&self, id: Ipv4Addr, route: Route) -> bool {
self.add_route_(id, route, false)
}
fn add_route_(&self, id: Ipv4Addr, route: Route, only_if_absent: bool) {
fn add_route_(&self, id: Ipv4Addr, route: Route, only_if_absent: bool) -> bool {
// 限制通道类型
match self.use_channel_type {
UseChannelType::P2p => {
if !route.is_p2p() {
return;
return false;
}
}
_ => {}
@@ -348,7 +393,7 @@ impl RouteTable {
if let Some((_, list)) = self.route_table.read().get(&id) {
for (x, _) in list {
if x.route_key() == key {
return;
return true;
}
}
}
@@ -361,11 +406,11 @@ impl RouteTable {
for (x, time) in list.iter_mut() {
if x.metric < route.metric && !self.first_latency {
//非优先延迟的情况下 不能比当前的路径更长
return;
return false;
}
if x.route_key() == key {
if only_if_absent {
return;
return true;
}
x.metric = route.metric;
x.rt = route.rt;
@@ -375,21 +420,7 @@ impl RouteTable {
}
}
if exist {
// 这个排序还有待优化,因为后加入的大概率排最后,被直接淘汰的概率也大,可能导致更好的通道被移除了
list.sort_by_key(|(k, _)| k.rt);
//如果延迟都稳定了,则去除多余通道
for (route, _) in list.iter() {
if route.rt == DEFAULT_RT {
return;
}
}
//延迟优先模式需要更多的通道探测延迟最低的路线
let limit_len = if self.first_latency {
self.channel_num + 2
} else {
self.channel_num
};
self.truncate_(list, limit_len);
} else {
if !self.first_latency {
if route.is_p2p() {
@@ -397,35 +428,34 @@ impl RouteTable {
list.retain(|(k, _)| k.is_p2p());
}
};
//增加路由表容量,避免波动
let limit_len = self.channel_num * 2;
list.sort_by_key(|(k, _)| k.rt);
self.truncate_(list, limit_len);
list.push((route, AtomicCell::new(Instant::now())));
}
return true;
}
fn truncate_(&self, list: &mut Vec<(Route, AtomicCell<Instant>)>, len: usize) {
if list.len() <= len {
return;
}
if self.first_latency {
//找到第一个p2p通道
if let Some(index) =
list.iter()
.enumerate()
.find_map(|(index, (route, _))| if route.is_p2p() { Some(index) } else { None })
{
if index >= len {
//保留第一个p2p通道
let route = list.remove(index);
list.truncate(len - 1);
list.push(route);
return;
}
}
}
list.truncate(len);
}
// 直接移除会导致通道不稳定,所以废弃这个方法,后面改用多余通道不发心跳包,从而让通道自动过期
// fn truncate_(&self, list: &mut Vec<(Route, AtomicCell<Instant>)>, len: usize) {
// if list.len() <= len {
// return;
// }
// if self.first_latency {
// //找到第一个p2p通道
// if let Some(index) =
// list.iter()
// .enumerate()
// .find_map(|(index, (route, _))| if route.is_p2p() { Some(index) } else { None })
// {
// if index >= len {
// //保留第一个p2p通道
// let route = list.remove(index);
// list.truncate(len - 1);
// list.push(route);
// return;
// }
// }
// }
// list.truncate(len);
// }
pub fn route(&self, id: &Ipv4Addr) -> Option<Vec<Route>> {
if let Some((_, v)) = self.route_table.read().get(id) {
Some(v.iter().map(|(i, _)| *i).collect())
+2 -2
View File
@@ -1,9 +1,9 @@
use crate::channel::context::ChannelContext;
use crate::channel::RouteKey;
pub trait RecvChannelHandler: Clone + Send + 'static {
pub trait RecvChannelHandler: Clone + Send + Sync + 'static {
fn handle(
&mut self,
&self,
buf: &mut [u8],
extend: &mut [u8],
route_key: RouteKey,
+1 -1
View File
@@ -39,7 +39,7 @@ impl Idle {
}
}
}
let sleep_time = self.read_idle - max;
let sleep_time = self.read_idle.checked_sub(max).unwrap_or_default();
return IdleType::Sleep(sleep_time);
}
}
+157 -52
View File
@@ -1,12 +1,17 @@
use anyhow::Context;
use std::net::{SocketAddr, UdpSocket};
use std::str::FromStr;
use tokio::sync::mpsc::channel;
use crate::channel::context::ChannelContext;
use crate::channel::handler::RecvChannelHandler;
use crate::channel::sender::AcceptSocketSender;
use crate::channel::sender::{AcceptSocketSender, ConnectUtil};
use crate::channel::socket::{bind_udp, LocalInterface};
use crate::channel::tcp_channel::tcp_listen;
use crate::channel::udp_channel::udp_listen;
#[cfg(feature = "ws")]
use crate::channel::ws_channel::ws_connect_accept;
use crate::util::limit::TrafficMeterMultiAddress;
use crate::util::StopManager;
pub mod context;
@@ -15,16 +20,24 @@ pub mod idle;
pub mod notify;
pub mod punch;
pub mod sender;
pub mod socket;
pub mod tcp_channel;
pub mod udp_channel;
#[cfg(feature = "ws")]
pub mod ws_channel;
pub const BUFFER_SIZE: usize = 1024 * 64;
// 这里留个坑,tcp是支持_TCP_MAX_PACKET_SIZE长度的,
// 但是缓存只用BUFFER_SIZE,会导致多余的数据接收不了
const TCP_MAX_PACKET_SIZE: usize = (1 << 24) - 1;
pub const BUFFER_SIZE: usize = 1024 * 16;
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum UseChannelType {
Relay,
P2p,
All,
}
impl UseChannelType {
pub fn is_only_relay(&self) -> bool {
self == &UseChannelType::Relay
@@ -36,6 +49,7 @@ impl UseChannelType {
self == &UseChannelType::All
}
}
impl FromStr for UseChannelType {
type Err = String;
@@ -48,15 +62,49 @@ impl FromStr for UseChannelType {
}
}
}
impl Default for UseChannelType {
fn default() -> Self {
UseChannelType::All
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum ConnectProtocol {
UDP,
TCP,
WS,
WSS,
}
impl ConnectProtocol {
#[inline]
pub fn is_tcp(&self) -> bool {
self == &ConnectProtocol::TCP
}
#[inline]
pub fn is_udp(&self) -> bool {
self == &ConnectProtocol::UDP
}
#[inline]
pub fn is_ws(&self) -> bool {
self == &ConnectProtocol::WS
}
#[inline]
pub fn is_wss(&self) -> bool {
self == &ConnectProtocol::WSS
}
pub fn is_transport(&self) -> bool {
self.is_tcp() || self.is_udp()
}
pub fn is_base_tcp(&self) -> bool {
self.is_tcp() || self.is_ws() || self.is_wss()
}
}
#[derive(Copy, Clone, Debug)]
pub struct Route {
pub is_tcp: bool,
pub protocol: ConnectProtocol,
index: usize,
pub addr: SocketAddr,
pub metric: u8,
@@ -68,11 +116,19 @@ pub struct RouteSortKey {
pub metric: u8,
pub rt: i64,
}
const DEFAULT_RT: i64 = 9999;
impl Route {
pub fn new(is_tcp: bool, index: usize, addr: SocketAddr, metric: u8, rt: i64) -> Self {
pub fn new(
protocol: ConnectProtocol,
index: usize,
addr: SocketAddr,
metric: u8,
rt: i64,
) -> Self {
Self {
is_tcp,
protocol,
index,
addr,
metric,
@@ -81,7 +137,7 @@ impl Route {
}
pub fn from(route_key: RouteKey, metric: u8, rt: i64) -> Self {
Self {
is_tcp: route_key.is_tcp,
protocol: route_key.protocol,
index: route_key.index,
addr: route_key.addr,
metric,
@@ -90,7 +146,7 @@ impl Route {
}
pub fn from_default_rt(route_key: RouteKey, metric: u8) -> Self {
Self {
is_tcp: route_key.is_tcp,
protocol: route_key.protocol,
index: route_key.index,
addr: route_key.addr,
metric,
@@ -99,7 +155,7 @@ impl Route {
}
pub fn route_key(&self) -> RouteKey {
RouteKey {
is_tcp: self.is_tcp,
protocol: self.protocol,
index: self.index,
addr: self.addr,
}
@@ -117,22 +173,24 @@ impl Route {
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, Debug)]
pub struct RouteKey {
is_tcp: bool,
protocol: ConnectProtocol,
index: usize,
pub addr: SocketAddr,
}
impl RouteKey {
pub(crate) fn new(is_tcp: bool, index: usize, addr: SocketAddr) -> Self {
pub(crate) const fn new(protocol: ConnectProtocol, index: usize, addr: SocketAddr) -> Self {
Self {
is_tcp,
protocol,
index,
addr,
}
}
pub fn is_tcp(&self) -> bool {
self.is_tcp
#[inline]
pub fn protocol(&self) -> ConnectProtocol {
self.protocol
}
#[inline]
pub fn index(&self) -> usize {
self.index
}
@@ -142,12 +200,16 @@ pub(crate) fn init_context(
ports: Vec<u16>,
use_channel_type: UseChannelType,
first_latency: bool,
is_tcp: bool,
protocol: ConnectProtocol,
packet_loss_rate: Option<f64>,
packet_delay: u32,
) -> anyhow::Result<(ChannelContext, mio::net::TcpListener)> {
default_interface: LocalInterface,
up_traffic_meter: Option<TrafficMeterMultiAddress>,
down_traffic_meter: Option<TrafficMeterMultiAddress>,
) -> anyhow::Result<(ChannelContext, std::net::TcpListener)> {
assert!(!ports.is_empty(), "not channel");
let mut udps = Vec::with_capacity(ports.len());
let mut main_udp_socket_v4 = Vec::with_capacity(ports.len());
let mut main_udp_socket_v6 = Vec::with_capacity(ports.len());
//检查系统是否支持ipv6
let use_ipv6 = match socket2::Socket::new(socket2::Domain::IPV6, socket2::Type::DGRAM, None) {
Ok(_) => true,
@@ -157,41 +219,33 @@ pub(crate) fn init_context(
}
};
for port in &ports {
//监听v6+v4双栈
let (socket, address) = if use_ipv6 {
let address: SocketAddr = format!("[::]:{}", port).parse().unwrap();
let socket = socket2::Socket::new(socket2::Domain::IPV6, socket2::Type::DGRAM, None)?;
socket
.set_only_v6(false)
.with_context(|| format!("set_only_v6 failed: {}", &address))?;
(socket, address)
let addr_v4: SocketAddr = format!("0.0.0.0:{}", port).parse().unwrap();
if use_ipv6 {
let (main_channel_v4, main_channel_v6) = bind_udp_v4_and_v6(*port, &default_interface)?;
main_udp_socket_v4.push(main_channel_v4);
main_udp_socket_v6.push(main_channel_v6);
} else {
let address: SocketAddr = format!("0.0.0.0:{}", port).parse().unwrap();
(
socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::DGRAM, None)?,
address,
)
};
if let Err(e) = socket.set_send_buffer_size(2 * 1024 * 1024) {
log::warn!("set_send_buffer_size {:?}", e);
let socket = bind_udp(addr_v4, &default_interface)?;
let main_channel_v4: UdpSocket = socket.into();
main_udp_socket_v4.push(main_channel_v4);
}
if let Err(e) = socket.set_recv_buffer_size(2 * 1024 * 1024) {
log::warn!("set_send_buffer_size {:?}", e);
}
socket
.bind(&address.into())
.with_context(|| format!("bind failed: {}", &address))?;
let main_channel: UdpSocket = socket.into();
udps.push(main_channel);
}
let mut main_udp_socket =
Vec::with_capacity(main_udp_socket_v4.len() + main_udp_socket_v6.len());
let v4_len = main_udp_socket_v4.len();
main_udp_socket.append(&mut main_udp_socket_v4);
main_udp_socket.append(&mut main_udp_socket_v6);
let context = ChannelContext::new(
udps,
main_udp_socket,
v4_len,
use_channel_type,
first_latency,
is_tcp,
protocol,
packet_loss_rate,
packet_delay,
use_ipv6,
up_traffic_meter,
down_traffic_meter,
default_interface,
);
let port = context.main_local_udp_port()?[0];
@@ -208,7 +262,13 @@ pub(crate) fn init_context(
let socket = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::STREAM, None)?;
(socket, address)
};
socket
.set_reuse_address(true)
.context("set_reuse_address")?;
#[cfg(unix)]
if let Err(e) = socket.set_reuse_port(true) {
log::warn!("set_reuse_port {:?}", e)
}
if let Err(e) = socket.bind(&address.into()) {
if ports[0] == 0 {
//端口可能冲突,则使用任意端口
@@ -228,33 +288,78 @@ pub(crate) fn init_context(
}
socket.listen(128)?;
socket.set_nonblocking(true)?;
socket.set_nodelay(false)?;
let tcp_listener = mio::net::TcpListener::from_std(socket.into());
Ok((context, tcp_listener))
socket.set_nodelay(true)?;
Ok((context, socket.into()))
}
fn bind_udp_v4_and_v6(
port: u16,
default_interface: &LocalInterface,
) -> anyhow::Result<(UdpSocket, UdpSocket)> {
let mut count = 0;
loop {
let addr_v4: SocketAddr = format!("0.0.0.0:{}", port).parse().unwrap();
let socket = bind_udp(addr_v4, default_interface)?;
if let Err(e) = socket.set_recv_buffer_size(2 * 1024 * 1024) {
log::warn!("set_recv_buffer_size {:?}", e);
}
let main_channel_v4: UdpSocket = socket.into();
let addr = main_channel_v4.local_addr()?;
let addr_v6: SocketAddr = format!("[::]:{}", addr.port()).parse().unwrap();
let socket = if port == 0 {
match bind_udp(addr_v6, default_interface) {
Ok(socket) => socket,
Err(e) => {
if count > 10 {
return Err(e);
}
if let Some(e) = e.downcast_ref::<std::io::Error>() {
if e.kind() == std::io::ErrorKind::AddrInUse {
count += 1;
continue;
}
}
Err(e)?
}
}
} else {
bind_udp(addr_v6, default_interface)?
};
if let Err(e) = socket.set_recv_buffer_size(2 * 1024 * 1024) {
log::warn!("set_recv_buffer_size {:?}", e);
}
let main_channel_v6: UdpSocket = socket.into();
return Ok((main_channel_v4, main_channel_v6));
}
}
pub(crate) fn init_channel<H>(
tcp_listener: mio::net::TcpListener,
tcp_listener: std::net::TcpListener,
context: ChannelContext,
stop_manager: StopManager,
recv_handler: H,
) -> anyhow::Result<(
AcceptSocketSender<Option<Vec<mio::net::UdpSocket>>>,
AcceptSocketSender<(mio::net::TcpStream, SocketAddr, Option<Vec<u8>>)>,
ConnectUtil,
)>
where
H: RecvChannelHandler,
{
let (tcp_connect_s, tcp_connect_r) = channel(16);
let (ws_connect_s, _ws_connect_r) = channel(16);
let connect_util = ConnectUtil::new(tcp_connect_s, ws_connect_s);
// udp监听,udp_socket_sender 用于NAT类型切换
let udp_socket_sender =
udp_listen(stop_manager.clone(), recv_handler.clone(), context.clone())?;
// 建立tcp监听,tcp_socket_sender 用于tcp 直连
let tcp_socket_sender = tcp_listen(
tcp_listen(
tcp_listener,
stop_manager.clone(),
tcp_connect_r,
recv_handler.clone(),
context.clone(),
stop_manager.clone(),
)?;
#[cfg(feature = "ws")]
ws_connect_accept(_ws_connect_r, recv_handler, context.clone(), stop_manager)?;
Ok((udp_socket_sender, tcp_socket_sender))
Ok((udp_socket_sender, connect_util))
}
+181 -78
View File
@@ -1,23 +1,51 @@
use std::collections::HashMap;
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::ops::{Div, Mul};
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use std::{io, thread};
use mio::net::TcpStream;
use crossbeam_utils::atomic::AtomicCell;
use rand::prelude::SliceRandom;
use rand::Rng;
use crate::channel::context::ChannelContext;
use crate::channel::sender::AcceptSocketSender;
use crate::external_route::ExternalRoute;
use crate::nat::NatTest;
use crate::channel::sender::ConnectUtil;
use crate::handle::CurrentDeviceInfo;
use crate::nat::{is_ipv4_global, NatTest};
use crate::proto::message::{PunchNatModel, PunchNatType};
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum PunchModel {
All,
IPv4,
IPv6,
All,
IPv4Tcp,
IPv4Udp,
IPv6Tcp,
IPv6Udp,
}
impl PunchModel {
pub fn use_tcp(&self) -> bool {
self != &PunchModel::IPv4Udp && self != &PunchModel::IPv6Udp
}
pub fn use_udp(&self) -> bool {
self != &PunchModel::IPv4Tcp && self != &PunchModel::IPv6Tcp
}
pub fn use_ipv6(&self) -> bool {
self == &PunchModel::All
|| self == &PunchModel::IPv6
|| self == &PunchModel::IPv6Tcp
|| self == &PunchModel::IPv6Udp
}
pub fn use_ipv4(&self) -> bool {
self == &PunchModel::All
|| self == &PunchModel::IPv4
|| self == &PunchModel::IPv4Tcp
|| self == &PunchModel::IPv4Udp
}
}
impl FromStr for PunchModel {
@@ -27,8 +55,15 @@ impl FromStr for PunchModel {
match s.to_lowercase().trim() {
"ipv4" => Ok(PunchModel::IPv4),
"ipv6" => Ok(PunchModel::IPv6),
"ipv4-tcp" => Ok(PunchModel::IPv4Tcp),
"ipv4-udp" => Ok(PunchModel::IPv4Udp),
"ipv6-tcp" => Ok(PunchModel::IPv6Tcp),
"ipv6-udp" => Ok(PunchModel::IPv6Udp),
"all" => Ok(PunchModel::All),
_ => Err(format!("not match '{}', enum: ipv4/ipv6/all", s)),
_ => Err(format!(
"not match '{}', enum: ipv4/ipv4-tcp/ipv4-udp/ipv6/ipv6-tcp/ipv6-udp/all",
s
)),
}
}
}
@@ -38,6 +73,33 @@ impl Default for PunchModel {
PunchModel::All
}
}
impl From<PunchModel> for PunchNatModel {
fn from(value: PunchModel) -> Self {
match value {
PunchModel::All => PunchNatModel::All,
PunchModel::IPv4 => PunchNatModel::IPv4,
PunchModel::IPv6 => PunchNatModel::IPv6,
PunchModel::IPv4Tcp => PunchNatModel::IPv4Tcp,
PunchModel::IPv4Udp => PunchNatModel::IPv4Udp,
PunchModel::IPv6Tcp => PunchNatModel::IPv6Tcp,
PunchModel::IPv6Udp => PunchNatModel::IPv6Udp,
}
}
}
impl Into<PunchModel> for PunchNatModel {
fn into(self) -> PunchModel {
match self {
PunchNatModel::All => PunchModel::All,
PunchNatModel::IPv4 => PunchModel::IPv4,
PunchNatModel::IPv6 => PunchModel::IPv6,
PunchNatModel::IPv4Tcp => PunchModel::IPv4Tcp,
PunchNatModel::IPv4Udp => PunchModel::IPv4Udp,
PunchNatModel::IPv6Tcp => PunchModel::IPv6Tcp,
PunchNatModel::IPv6Udp => PunchModel::IPv6Udp,
}
}
}
#[derive(Clone, Debug)]
pub struct NatInfo {
@@ -47,8 +109,10 @@ pub struct NatInfo {
pub nat_type: NatType,
pub(crate) local_ipv4: Option<Ipv4Addr>,
pub(crate) ipv6: Option<Ipv6Addr>,
pub(crate) udp_ports: Vec<u16>,
pub udp_ports: Vec<u16>,
pub tcp_port: u16,
pub public_tcp_port: u16,
pub punch_model: PunchModel,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
@@ -57,6 +121,29 @@ pub enum NatType {
Cone,
}
impl NatType {
pub fn is_cone(&self) -> bool {
self == &NatType::Cone
}
}
impl From<NatType> for PunchNatType {
fn from(value: NatType) -> Self {
match value {
NatType::Symmetric => PunchNatType::Symmetric,
NatType::Cone => PunchNatType::Cone,
}
}
}
impl Into<NatType> for PunchNatType {
fn into(self) -> NatType {
match self {
PunchNatType::Symmetric => NatType::Symmetric,
PunchNatType::Cone => NatType::Cone,
}
}
}
impl NatInfo {
pub fn new(
mut public_ips: Vec<Ipv4Addr>,
@@ -66,7 +153,9 @@ impl NatInfo {
mut ipv6: Option<Ipv6Addr>,
udp_ports: Vec<u16>,
tcp_port: u16,
public_tcp_port: u16,
mut nat_type: NatType,
punch_model: PunchModel,
) -> Self {
public_ips.retain(|ip| {
!ip.is_multicast()
@@ -96,29 +185,33 @@ impl NatInfo {
ipv6,
udp_ports,
tcp_port,
public_tcp_port,
nat_type,
punch_model,
}
}
pub fn update_addr(&mut self, index: usize, ip: Ipv4Addr, port: u16) {
pub fn update_addr(&mut self, index: usize, ip: Ipv4Addr, port: u16) -> bool {
let mut updated = false;
if port != 0 {
if let Some(public_port) = self.public_ports.get_mut(index) {
if *public_port != port {
updated = true;
log::info!("端口变化={}:{} index={}", ip, port, index)
}
*public_port = port;
}
}
if !ip.is_multicast()
&& !ip.is_broadcast()
&& !ip.is_unspecified()
&& !ip.is_loopback()
&& !ip.is_private()
{
if is_ipv4_global(&ip) {
if !self.public_ips.contains(&ip) {
self.public_ips.push(ip);
updated = true;
log::info!("ip变化={},{:?}", ip, self.public_ips)
}
}
updated
}
pub fn update_tcp_port(&mut self, port: u16) {
self.public_tcp_port = port;
}
pub fn local_ipv4(&self) -> Option<Ipv4Addr> {
self.local_ipv4
@@ -185,20 +278,18 @@ pub struct Punch {
port_vec: Vec<u16>,
port_index: HashMap<Ipv4Addr, usize>,
punch_model: PunchModel,
is_tcp: bool,
tcp_socket_sender: AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>,
external_route: ExternalRoute,
connect_util: ConnectUtil,
nat_test: NatTest,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
}
impl Punch {
pub fn new(
context: ChannelContext,
punch_model: PunchModel,
is_tcp: bool,
tcp_socket_sender: AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>,
external_route: ExternalRoute,
connect_util: ConnectUtil,
nat_test: NatTest,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
) -> Self {
let mut port_vec: Vec<u16> = (1..65535).collect();
port_vec.push(65535);
@@ -209,35 +300,22 @@ impl Punch {
port_vec,
port_index: HashMap::new(),
punch_model,
is_tcp,
tcp_socket_sender,
external_route,
connect_util,
nat_test,
current_device,
}
}
}
impl Punch {
fn connect_tcp(&self, buf: &[u8], addr: SocketAddr) -> bool {
fn connect_tcp(&self, buf: &[u8], addr: SocketAddr) {
if self.nat_test.is_local_address(true, addr) {
return false;
return;
}
// mio是非阻塞的,不能立马判断是否能连接成功,所以用标准库的tcp
match std::net::TcpStream::connect_timeout(&addr, Duration::from_millis(100)) {
Ok(tcp_stream) => {
if tcp_stream.set_nonblocking(true).is_err() {
return false;
}
return self
.tcp_socket_sender
.try_add_socket((TcpStream::from_std(tcp_stream), addr, Some(buf.to_vec())))
.is_ok();
}
Err(e) => {
log::warn!("连接到tcp失败,addr={},err={}", addr, e);
}
if addr.ip().is_unspecified() || addr.port() == 0 {
return;
}
false
self.connect_util.try_connect_tcp_punch(buf.to_vec(), addr);
}
pub fn punch(
&mut self,
@@ -245,46 +323,65 @@ impl Punch {
id: Ipv4Addr,
mut nat_info: NatInfo,
punch_tcp: bool,
count: usize,
) -> io::Result<()> {
if self.context.route_table.no_need_punch(&id) {
log::info!("已打洞成功,无需打洞:{:?}", id);
return Ok(());
}
let device_info = self.current_device.load();
nat_info
.public_ips
.retain(|ip| self.external_route.route(&ip).is_none());
nat_info
.retain(|ip| is_ipv4_global(ip) && device_info.not_in_network(*ip));
nat_info.public_ports.retain(|port| *port != 0);
nat_info.udp_ports.retain(|port| *port != 0);
nat_info.local_ipv4 = nat_info
.local_ipv4
.filter(|ip| self.external_route.route(&ip).is_none());
nat_info.ipv6.filter(|ip| {
if let Some(ip) = ip.to_ipv4_mapped() {
self.external_route.route(&ip).is_none()
} else {
true
}
});
if punch_tcp && self.is_tcp && nat_info.tcp_port != 0 {
.filter(|ip| device_info.not_in_network(*ip));
if punch_tcp && self.punch_model.use_tcp() && nat_info.punch_model.use_tcp() {
//向tcp发起连接
if let Some(ipv6_addr) = nat_info.local_tcp_ipv6addr() {
if self.connect_tcp(buf, ipv6_addr) {
// return Ok(());
if self.punch_model.use_ipv6() && nat_info.punch_model.use_ipv6() {
if let Some(ipv6_addr) = nat_info.local_tcp_ipv6addr() {
self.connect_tcp(buf, ipv6_addr)
}
}
//向tcp发起连接
if let Some(ipv4_addr) = nat_info.local_tcp_ipv4addr() {
if self.connect_tcp(buf, ipv4_addr) {
// return Ok(());
if self.punch_model.use_ipv4() && nat_info.punch_model.use_ipv4() {
if let Some(ipv4_addr) = nat_info.local_tcp_ipv4addr() {
self.connect_tcp(buf, ipv4_addr)
}
}
if nat_info.nat_type == NatType::Cone && nat_info.public_ips.len() == 1 {
let addr =
SocketAddr::V4(SocketAddrV4::new(nat_info.public_ips[0], nat_info.tcp_port));
if self.connect_tcp(buf, addr) {
// return Ok(());
for ip in &nat_info.public_ips {
let addr = SocketAddr::V4(SocketAddrV4::new(*ip, nat_info.tcp_port));
self.connect_tcp(buf, addr);
}
if nat_info.nat_type.is_cone() && nat_info.public_tcp_port != 0 {
for ip in &nat_info.public_ips {
let addr = SocketAddr::V4(SocketAddrV4::new(*ip, nat_info.public_tcp_port));
self.connect_tcp(buf, addr);
}
}
}
}
if !self.punch_model.use_udp() || !nat_info.punch_model.use_udp() {
return Ok(());
}
let channel_num = self.context.channel_num();
let main_len = self.context.main_len();
if self.punch_model.use_ipv6() && nat_info.punch_model.use_ipv6() {
for index in channel_num..main_len {
if let Some(ipv6_addr) = nat_info.local_udp_ipv6addr(index) {
if !self.nat_test.is_local_address(false, ipv6_addr) {
let rs = self.context.send_main_udp(index, buf, ipv6_addr);
log::info!("发送到ipv6地址:{:?},rs={:?} {}", ipv6_addr, rs, id);
}
}
}
}
if !self.punch_model.use_ipv4() || !nat_info.punch_model.use_ipv4() {
return Ok(());
}
for index in 0..channel_num {
if let Some(ipv4_addr) = nat_info.local_udp_ipv4addr(index) {
if !self.nat_test.is_local_address(false, ipv4_addr) {
@@ -292,20 +389,23 @@ impl Punch {
}
}
}
if self.punch_model != PunchModel::IPv4 {
for index in 0..channel_num {
if let Some(ipv6_addr) = nat_info.local_udp_ipv6addr(index) {
if !self.nat_test.is_local_address(false, ipv6_addr) {
let rs = self.context.send_main_udp(index, buf, ipv6_addr);
log::info!("发送到ipv6地址:{:?},rs={:?}", ipv6_addr, rs);
if rs.is_ok() && self.punch_model == PunchModel::IPv6 {
return Ok(());
}
// 可能是开放了端口的,需要打洞
for index in 0..channel_num {
for port in &nat_info.udp_ports {
if *port == 0 {
continue;
}
for ip in &nat_info.public_ips {
if ip.is_unspecified() {
continue;
}
let addr = SocketAddrV4::new(*ip, *port);
let _ = self.context.send_main_udp(index, buf, addr.into());
thread::sleep(Duration::from_millis(3));
}
}
}
match nat_info.nat_type {
NatType::Symmetric => {
// 假设对方绑定n个端口,通过NAT对外映射出n个 公网ip:公网端口,自己随机尝试k次的情况下
@@ -316,7 +416,11 @@ impl Punch {
//预测范围内最多发送max_k1个包
let max_k1 = 60;
//全局最多发送max_k2个包
let max_k2 = rand::thread_rng().gen_range(600..800);
let mut max_k2: usize = rand::thread_rng().gen_range(600..800);
if count > 2 {
//递减探测规模
max_k2 = max_k2.mul(2).div(count).max(max_k1 as usize);
}
let port = nat_info.public_ports.get(0).map(|e| *e).unwrap_or(0);
if nat_info.public_port_range < max_k1 * 3 {
//端口变化不大时,在预测的范围内随机发送
@@ -332,8 +436,7 @@ impl Punch {
} else {
(max_port - min_port + 1) as usize
};
let mut nums: Vec<u16> = (min_port..max_port).collect();
nums.push(max_port);
let mut nums: Vec<u16> = (min_port..=max_port).collect();
nums.shuffle(&mut rand::thread_rng());
self.punch_symmetric(&nums[..k], buf, &nat_info.public_ips, max_k1 as usize)?;
}
@@ -397,7 +500,7 @@ impl Punch {
}
let addr = SocketAddr::V4(SocketAddrV4::new(*pub_ip, *port));
self.context.send_main_udp(0, buf, addr)?;
thread::sleep(Duration::from_millis(2));
thread::sleep(Duration::from_millis(3));
}
}
Ok(ports.len())
+140 -54
View File
@@ -1,17 +1,19 @@
use std::collections::HashMap;
use std::io;
use std::net::Ipv4Addr;
use std::net::{Ipv4Addr, SocketAddr};
use std::sync::mpsc::{SyncSender, TrySendError};
use std::sync::Arc;
use crossbeam_utils::atomic::AtomicCell;
use mio::Token;
use parking_lot::Mutex;
use tokio::sync::mpsc::Sender;
use crate::channel::context::ChannelContext;
use crate::channel::notify::{AcceptNotify, WritableNotify};
use crate::channel::notify::AcceptNotify;
use crate::cipher::Cipher;
use crate::compression::Compressor;
use crate::external_route::ExternalRoute;
use crate::handle::CurrentDeviceInfo;
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
use crate::protocol;
use crate::protocol::{ip_turn_packet, NetPacket};
@@ -21,7 +23,10 @@ pub struct IpPacketSender {
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
compressor: Compressor,
client_cipher: Cipher,
server_cipher: Cipher,
ip_route: ExternalRoute,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
allow_wire_guard: bool,
}
impl IpPacketSender {
@@ -30,14 +35,20 @@ impl IpPacketSender {
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
compressor: Compressor,
client_cipher: Cipher,
server_cipher: Cipher,
ip_route: ExternalRoute,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
allow_wire_guard: bool,
) -> Self {
Self {
context,
current_device,
compressor,
client_cipher,
server_cipher,
ip_route,
device_map,
allow_wire_guard,
}
}
pub fn self_virtual_ip(&self) -> Ipv4Addr {
@@ -58,19 +69,54 @@ impl IpPacketSender {
if let Some(v) = self.ip_route.route(&dest_ip) {
dest_ip = v;
}
if dest_ip.is_multicast() || dest_ip.is_broadcast() || dest_ip == device_info.broadcast_ip {
if dest_ip.is_multicast() {
//广播
dest_ip = Ipv4Addr::BROADCAST;
}
let mut net_packet = NetPacket::new0(data_len, buf)?;
let mut auxiliary = NetPacket::new(auxiliary_buf)?;
net_packet.set_default_version();
net_packet.set_protocol(protocol::Protocol::IpTurn);
net_packet.set_transport_protocol(ip_turn_packet::Protocol::Ipv4.into());
net_packet.first_set_ttl(6);
net_packet.set_source(src_ip);
net_packet.set_destination(dest_ip);
if self.allow_wire_guard {
if dest_ip.is_broadcast() || dest_ip == device_info.broadcast_ip {
let exists_wg = self
.device_map
.lock()
.1
.values()
.any(|v| v.status.is_online() && v.wireguard);
if exists_wg {
send_to_wg_broadcast(
&self.context,
&net_packet,
&self.server_cipher,
&device_info,
)?;
}
} else {
let guard = self.device_map.lock();
if let Some(peer_info) = guard.1.get(&dest_ip) {
if peer_info.wireguard {
if peer_info.status.is_offline() {
return Ok(());
}
drop(guard);
send_to_wg(
&self.context,
&mut net_packet,
&self.server_cipher,
&device_info,
)?;
return Ok(());
}
}
}
}
let mut auxiliary = NetPacket::new(auxiliary_buf)?;
let mut net_packet = if self.compressor.compress(&net_packet, &mut auxiliary)? {
auxiliary.set_default_version();
@@ -84,20 +130,19 @@ impl IpPacketSender {
net_packet
};
self.client_cipher.encrypt_ipv4(&mut net_packet)?;
if dest_ip.is_broadcast() {
if dest_ip.is_broadcast() || dest_ip == device_info.broadcast_ip {
//走服务端广播
self.context
.send_default(net_packet.buffer(), device_info.connect_server)?;
.send_default(&net_packet, device_info.connect_server)?;
return Ok(());
}
// if u32::from_be_bytes(dest_ip.octets()) & u32::from_be_bytes(device_info.virtual_netmask.octets())
// != u32::from_be_bytes(device_info.virtual_network.octets()) {
// //不是一个网段的直接忽略
// return Ok(());
// }
if device_info.not_in_network(dest_ip) {
//不是一个网段的直接忽略
return Ok(());
}
self.context.send_ipv4_by_id(
net_packet.buffer(),
&net_packet,
&dest_ip,
device_info.connect_server,
device_info.status.online(),
@@ -106,6 +151,40 @@ impl IpPacketSender {
}
}
pub fn send_to_wg_broadcast(
sender: &ChannelContext,
net_packet: &NetPacket<&mut [u8]>,
server_cipher: &Cipher,
current_device: &CurrentDeviceInfo,
) -> anyhow::Result<()> {
let mut copy_packet = NetPacket::new0(net_packet.data_len(), [0; 65536])?;
copy_packet.set_default_version();
copy_packet.set_protocol(protocol::Protocol::IpTurn);
copy_packet.set_transport_protocol(ip_turn_packet::Protocol::WGIpv4.into());
copy_packet.first_set_ttl(6);
copy_packet.set_source(net_packet.source());
copy_packet.set_destination(net_packet.destination());
copy_packet.set_gateway_flag(true);
copy_packet.set_payload(net_packet.payload())?;
server_cipher.encrypt_ipv4(&mut copy_packet)?;
sender.send_default(&copy_packet, current_device.connect_server)?;
Ok(())
}
pub fn send_to_wg(
sender: &ChannelContext,
net_packet: &mut NetPacket<&mut [u8]>,
server_cipher: &Cipher,
current_device: &CurrentDeviceInfo,
) -> anyhow::Result<()> {
net_packet.set_transport_protocol(ip_turn_packet::Protocol::WGIpv4.into());
net_packet.set_gateway_flag(true);
server_cipher.encrypt_ipv4(net_packet)?;
sender.send_default(&net_packet, current_device.connect_server)?;
Ok(())
}
pub struct AcceptSocketSender<T> {
sender: SyncSender<T>,
notify: AcceptNotify,
@@ -134,53 +213,60 @@ impl<T> AcceptSocketSender<T> {
}
}
}
#[derive(Clone)]
pub struct PacketSender {
inner: Arc<PacketSenderInner>,
sender: Sender<Vec<u8>>,
}
impl PacketSender {
pub fn new(notify: WritableNotify, buffer: SyncSender<Vec<u8>>, token: Token) -> Self {
Self {
inner: Arc::new(PacketSenderInner {
token,
notify,
buffer,
}),
}
pub fn new(sender: Sender<Vec<u8>>) -> Self {
Self { sender }
}
#[inline]
pub fn try_send(&self, buf: &[u8]) -> io::Result<()> {
self.inner.try_send(buf)
}
pub fn shutdown(&self) -> io::Result<()> {
self.inner.shutdown()
}
}
pub struct PacketSenderInner {
token: Token,
notify: WritableNotify,
buffer: SyncSender<Vec<u8>>,
}
impl PacketSenderInner {
#[inline]
fn try_send(&self, buf: &[u8]) -> io::Result<()> {
let len = buf.len();
let mut buf_vec = Vec::with_capacity(buf.len() + 4);
buf_vec.extend_from_slice(&[0, 0, (len >> 8) as u8, (len & 0xFF) as u8]);
buf_vec.extend_from_slice(buf);
match self.buffer.try_send(buf_vec) {
Ok(_) => self.notify.notify(self.token, true),
Err(e) => match e {
TrySendError::Disconnected(_) => Err(io::Error::from(io::ErrorKind::WriteZero)),
TrySendError::Full(_) => Err(io::Error::from(io::ErrorKind::WouldBlock)),
},
match self.sender.try_send(buf.to_vec()) {
Ok(_) => Ok(()),
Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => Err(io::Error::new(
io::ErrorKind::WouldBlock,
"通道已满,发生丢包",
)),
Err(_) => Err(io::Error::new(
io::ErrorKind::ConnectionRefused,
"通道关闭,发生丢包",
)),
}
}
fn shutdown(&self) -> io::Result<()> {
self.notify.notify(self.token, false)
}
#[derive(Clone)]
pub struct ConnectUtil {
connect_tcp: Sender<(Vec<u8>, Option<u16>, SocketAddr)>,
connect_ws: Sender<(Vec<u8>, String)>,
}
impl ConnectUtil {
pub fn new(
connect_tcp: Sender<(Vec<u8>, Option<u16>, SocketAddr)>,
connect_ws: Sender<(Vec<u8>, String)>,
) -> Self {
Self {
connect_tcp,
connect_ws,
}
}
pub fn try_connect_tcp(&self, buf: Vec<u8>, addr: SocketAddr) {
if self.connect_tcp.try_send((buf, None, addr)).is_err() {
log::warn!("try_connect_tcp failed {}", addr);
}
}
pub fn try_connect_tcp_punch(&self, buf: Vec<u8>, addr: SocketAddr) {
// 打洞的连接可以绑定随机端口
if self.connect_tcp.try_send((buf, Some(0), addr)).is_err() {
log::warn!("try_connect_tcp failed {}", addr);
}
}
pub fn try_connect_ws(&self, buf: Vec<u8>, addr: String) {
if self.connect_ws.try_send((buf, addr)).is_err() {
log::warn!("try_connect_ws failed");
}
}
}
+138
View File
@@ -0,0 +1,138 @@
use anyhow::{anyhow, Context};
use network_interface::{NetworkInterface, NetworkInterfaceConfig};
use socket2::Protocol;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;
pub trait VntSocketTrait {
fn set_ip_unicast_if(&self, _interface: &LocalInterface) -> anyhow::Result<()> {
Ok(())
}
}
#[derive(Clone, Debug, Default)]
pub struct LocalInterface {
index: u32,
#[cfg(unix)]
name: Option<String>,
}
pub async fn connect_tcp(
addr: SocketAddr,
bind_port: u16,
default_interface: &LocalInterface,
) -> anyhow::Result<tokio::net::TcpStream> {
let socket = create_tcp0(addr.is_ipv4(), bind_port, default_interface)?;
Ok(socket.connect(addr).await?)
}
pub fn create_tcp(
v4: bool,
default_interface: &LocalInterface,
) -> anyhow::Result<tokio::net::TcpSocket> {
create_tcp0(v4, 0, default_interface)
}
pub fn create_tcp0(
v4: bool,
bind_port: u16,
default_interface: &LocalInterface,
) -> anyhow::Result<tokio::net::TcpSocket> {
let socket = if v4 {
socket2::Socket::new(
socket2::Domain::IPV4,
socket2::Type::STREAM,
Some(Protocol::TCP),
)?
} else {
socket2::Socket::new(
socket2::Domain::IPV6,
socket2::Type::STREAM,
Some(Protocol::TCP),
)?
};
if v4 {
if let Err(e) = socket.set_ip_unicast_if(default_interface) {
log::warn!("set_ip_unicast_if {:?}", e)
}
}
if bind_port != 0 {
socket
.set_reuse_address(true)
.context("set_reuse_address")?;
#[cfg(unix)]
if let Err(e) = socket.set_reuse_port(true) {
log::warn!("set_reuse_port {:?}", e)
}
if v4 {
let addr: SocketAddr = format!("0.0.0.0:{}", bind_port).parse().unwrap();
socket.bind(&addr.into())?;
} else {
socket.set_only_v6(true)?;
let addr: SocketAddr = format!("[::]:{}", bind_port).parse().unwrap();
socket.bind(&addr.into())?;
}
}
socket.set_nonblocking(true)?;
socket.set_nodelay(true)?;
Ok(tokio::net::TcpSocket::from_std_stream(socket.into()))
}
pub fn bind_udp_ops(
addr: SocketAddr,
only_v6: bool,
default_interface: &LocalInterface,
) -> anyhow::Result<socket2::Socket> {
let socket = if addr.is_ipv4() {
let socket = socket2::Socket::new(
socket2::Domain::IPV4,
socket2::Type::DGRAM,
Some(Protocol::UDP),
)?;
if let Err(e) = socket.set_ip_unicast_if(default_interface) {
log::warn!("set_ip_unicast_if {:?}", e)
}
socket
} else {
let socket = socket2::Socket::new(
socket2::Domain::IPV6,
socket2::Type::DGRAM,
Some(Protocol::UDP),
)?;
socket
.set_only_v6(only_v6)
.with_context(|| format!("set_only_v6 failed: {}", &addr))?;
socket
};
socket.set_nonblocking(true)?;
socket.bind(&addr.into())?;
Ok(socket)
}
pub fn bind_udp(
addr: SocketAddr,
default_interface: &LocalInterface,
) -> anyhow::Result<socket2::Socket> {
bind_udp_ops(addr, true, default_interface).with_context(|| format!("{}", addr))
}
pub fn get_interface(dest_name: String) -> anyhow::Result<(LocalInterface, Ipv4Addr)> {
let network_interfaces = NetworkInterface::show()?;
for iface in network_interfaces {
if iface.name == dest_name {
for addr in iface.addr {
if let IpAddr::V4(ip) = addr.ip() {
return Ok((
LocalInterface {
index: iface.index,
#[cfg(unix)]
name: Some(iface.name),
},
ip,
));
}
}
}
}
Err(anyhow!("No network card with name {} found", dest_name))
}
+46
View File
@@ -0,0 +1,46 @@
use crate::channel::socket::{LocalInterface, VntSocketTrait};
#[cfg(any(target_os = "linux", target_os = "macos"))]
use anyhow::Context;
#[cfg(target_os = "linux")]
impl VntSocketTrait for socket2::Socket {
fn set_ip_unicast_if(&self, interface: &LocalInterface) -> anyhow::Result<()> {
if let Some(name) = &interface.name {
self.bind_device(Some(name.as_bytes()))
.context("bind_device")?;
}
Ok(())
}
}
#[cfg(target_os = "macos")]
impl VntSocketTrait for socket2::Socket {
fn set_ip_unicast_if(&self, interface: &LocalInterface) -> anyhow::Result<()> {
if interface.index != 0 {
self.bind_device_by_index_v4(std::num::NonZeroU32::new(interface.index))
.with_context(|| format!("bind_device_by_index_v4 {:?}", interface))?;
}
Ok(())
}
}
#[cfg(target_os = "android")]
impl VntSocketTrait for socket2::Socket {
fn set_ip_unicast_if(&self, _interface: &LocalInterface) -> anyhow::Result<()> {
Ok(())
}
}
// #[cfg(any(target_os = "linux", target_os = "macos"))]
// pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// match get_interface(dest_ip) {
// Ok(iface) => return Ok(iface),
// Err(e) => {
// log::warn!("not find interface e={:?},ip={}", e, dest_ip);
// }
// }
// // 应该再查路由表找到默认路由的
// Ok(LocalInterface::default())
// }
// #[cfg(target_os = "android")]
// pub fn get_best_interface(_dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// Ok(LocalInterface::default())
// }
+56
View File
@@ -0,0 +1,56 @@
use std::mem;
use std::os::windows::io::AsRawSocket;
use windows_sys::core::PCSTR;
use windows_sys::Win32::Networking::WinSock::{
htonl, setsockopt, IPPROTO_IP, IP_UNICAST_IF, SOCKET_ERROR,
};
use crate::channel::socket::{LocalInterface, VntSocketTrait};
impl VntSocketTrait for socket2::Socket {
fn set_ip_unicast_if(&self, interface: &LocalInterface) -> anyhow::Result<()> {
let index = interface.index;
if index == 0 {
return Ok(());
}
let raw_socket = self.as_raw_socket();
let result = unsafe {
let best_interface = htonl(index);
setsockopt(
raw_socket as usize,
IPPROTO_IP,
IP_UNICAST_IF,
&best_interface as *const _ as PCSTR,
mem::size_of_val(&best_interface) as i32,
)
};
if result == SOCKET_ERROR {
Err(anyhow::anyhow!(
"Failed to set IP_UNICAST_IF: {:?} {}",
std::io::Error::last_os_error(),
index
))?;
}
Ok(())
}
}
// pub fn get_best_interface(dest_ip: Ipv4Addr) -> anyhow::Result<LocalInterface> {
// // 获取最佳接口
// let index = unsafe {
// let mut dest: SOCKADDR_IN = mem::zeroed();
// dest.sin_family = AF_INET as u16;
// dest.sin_addr.S_un.S_addr = u32::from_ne_bytes(dest_ip.octets());
//
// let mut index: u32 = 0;
// if GetBestInterfaceEx(&dest as *const _ as *mut SOCKADDR, &mut index) != 0 {
// Err(anyhow::anyhow!(
// "Failed to GetBestInterfaceEx: {:?}",
// std::io::Error::last_os_error()
// ))?;
// }
// index
// };
// Ok(LocalInterface { index })
// }
+166 -422
View File
@@ -1,468 +1,212 @@
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::{Shutdown, SocketAddr};
#[cfg(any(unix))]
use std::os::fd::FromRawFd;
#[cfg(any(unix))]
use std::os::fd::IntoRawFd;
use anyhow::{anyhow, Context};
use std::net::SocketAddr;
#[cfg(unix)]
use std::os::unix::io::AsRawFd;
#[cfg(windows)]
use std::os::windows::io::FromRawSocket;
#[cfg(windows)]
use std::os::windows::io::IntoRawSocket;
use std::sync::mpsc::{sync_channel, Receiver, SyncSender, TryRecvError, TrySendError};
use std::{io, thread};
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Registry, Token, Waker};
use std::os::windows::io::AsRawSocket;
use std::thread;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::tcp::OwnedReadHalf;
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc::{channel, Receiver};
use crate::channel::context::ChannelContext;
use crate::channel::handler::RecvChannelHandler;
use crate::channel::notify::{AcceptNotify, WritableNotify};
use crate::channel::sender::{AcceptSocketSender, PacketSender};
use crate::channel::{RouteKey, BUFFER_SIZE};
use crate::channel::sender::PacketSender;
use crate::channel::socket::create_tcp0;
use crate::channel::{ConnectProtocol, RouteKey, BUFFER_SIZE, TCP_MAX_PACKET_SIZE};
use crate::util::StopManager;
const SERVER: Token = Token(0);
const NOTIFY: Token = Token(1);
/// 监听tcp端口,等待客户端连接
pub fn tcp_listen<H>(
tcp_server: TcpListener,
stop_manager: StopManager,
tcp_server: std::net::TcpListener,
receiver: Receiver<(Vec<u8>, Option<u16>, SocketAddr)>,
recv_handler: H,
context: ChannelContext,
) -> anyhow::Result<AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>>
stop_manager: StopManager,
) -> anyhow::Result<()>
where
H: RecvChannelHandler,
{
let (tcp_sender, tcp_receiver) = sync_channel(64);
let poll = Poll::new()?;
let waker = AcceptNotify::new(Waker::new(poll.registry(), NOTIFY)?);
let accept = AcceptSocketSender::new(waker.clone(), tcp_sender);
let worker = {
let waker = waker.clone();
stop_manager.add_listener("tcp_listen".into(), move || {
if let Err(e) = waker.stop() {
log::error!("{:?}", e);
}
})?
};
let (stop_sender, stop_receiver) = tokio::sync::oneshot::channel::<()>();
let worker = stop_manager.add_listener("tcpChannel".into(), move || {
let _ = stop_sender.send(());
})?;
let bind_port = tcp_server.local_addr()?.port();
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.context("tcp tokio runtime build failed")?;
thread::Builder::new()
.name("tcpRead".into())
.name("tcpChannel".into())
.spawn(move || {
if let Err(e) = tcp_listen0(
poll,
tcp_server,
&stop_manager,
waker,
tcp_receiver,
recv_handler,
context,
) {
log::error!("{:?}", e);
}
runtime.spawn(async move {
{
let recv_handler = recv_handler.clone();
let context = context.clone();
tokio::spawn(async move {
if let Err(e) = tcp_accept(tcp_server, recv_handler, context).await {
log::warn!("tcp_listen {:?}", e);
}
});
}
tokio::spawn(async move {
connect_tcp_handle(receiver, recv_handler, context, bind_port).await
});
});
runtime.block_on(async {
let _ = stop_receiver.await;
});
runtime.shutdown_background();
worker.stop_all();
})?;
Ok(accept)
})
.context("tcp thread build failed")?;
Ok(())
}
fn tcp_listen0<H>(
mut poll: Poll,
mut tcp_server: TcpListener,
stop_manager: &StopManager,
accept_notify: AcceptNotify,
accept_tcp_receiver: Receiver<(TcpStream, SocketAddr, Option<Vec<u8>>)>,
mut recv_handler: H,
async fn connect_tcp_handle<H>(
mut receiver: Receiver<(Vec<u8>, Option<u16>, SocketAddr)>,
recv_handler: H,
context: ChannelContext,
listener_bind_port: u16,
) where
H: RecvChannelHandler,
{
while let Some((data, bind_port, addr)) = receiver.recv().await {
let recv_handler = recv_handler.clone();
let context = context.clone();
let bind_port = if let Some(bind_port) = bind_port {
bind_port
} else {
listener_bind_port
};
tokio::spawn(async move {
if let Err(e) = connect_tcp0(data, addr, recv_handler, context, bind_port).await {
log::warn!("连接失败,链接终止:{:?},{:?}", addr, e);
}
});
}
}
async fn connect_tcp0<H>(
data: Vec<u8>,
addr: SocketAddr,
recv_handler: H,
context: ChannelContext,
bind_port: u16,
) -> anyhow::Result<()>
where
H: RecvChannelHandler,
{
let socket = if bind_port != 0 {
match create_tcp0(addr.is_ipv4(), bind_port, context.default_interface()) {
Ok(socket) => socket,
Err(e) => {
log::warn!("{:?}", e);
create_tcp0(addr.is_ipv4(), 0, context.default_interface())?
}
}
} else {
create_tcp0(addr.is_ipv4(), 0, context.default_interface())?
};
let mut stream = tokio::time::timeout(Duration::from_secs(3), socket.connect(addr)).await??;
tcp_write(&mut stream, &data).await?;
tcp_stream_handle(stream, addr, recv_handler, context).await;
Ok(())
}
async fn tcp_accept<H>(
tcp_server: std::net::TcpListener,
recv_handler: H,
context: ChannelContext,
) -> anyhow::Result<()>
where
H: RecvChannelHandler,
{
let (tcp_sender, tcp_receiver) = sync_channel(64);
let write_waker = init_writable_handler(tcp_receiver, stop_manager.clone(), context.clone())?;
poll.registry()
.register(&mut tcp_server, SERVER, Interest::READABLE)?;
let mut events = Events::with_capacity(1024);
let tcp_server = TcpListener::from_std(tcp_server)?;
let mut read_map: HashMap<Token, (RouteKey, TcpStream, Box<[u8; BUFFER_SIZE]>, usize)> =
HashMap::with_capacity(32);
let mut extend = [0; BUFFER_SIZE];
loop {
if let Err(e) = poll.poll(&mut events, None) {
crate::ignore_io_interrupted(e)?;
continue;
}
for event in events.iter() {
match event.token() {
SERVER => loop {
match tcp_server.accept() {
Ok((stream, addr)) => {
accept_handle(
stream,
addr,
None,
&write_waker,
&mut read_map,
&tcp_sender,
poll.registry(),
)?;
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
break;
}
return Err(e)?;
}
}
},
NOTIFY => {
if accept_notify.is_stop() {
return Ok(());
}
if accept_notify.is_add_socket() {
while let Ok((stream, addr, init_buf)) = accept_tcp_receiver.try_recv() {
accept_handle(
stream,
addr,
init_buf,
&write_waker,
&mut read_map,
&tcp_sender,
poll.registry(),
)?;
}
}
}
token => {
if event.is_readable() {
if let Err(e) = readable_handle(
&token,
&mut read_map,
&mut recv_handler,
&context,
&mut extend,
) {
closed_handle_r(&token, &mut read_map);
log::warn!("{:?}", e);
if let Err(e) = write_waker.notify(token, false) {
log::warn!("{:?}", e);
}
}
} else {
closed_handle_r(&token, &mut read_map);
if let Err(e) = write_waker.notify(token, false) {
log::warn!("{:?}", e);
}
}
}
}
}
let (stream, addr) = tcp_server.accept().await?;
tcp_stream_handle(stream, addr, recv_handler.clone(), context.clone()).await;
}
}
/// 处理写事件
fn init_writable_handler(
receiver: Receiver<(TcpStream, Token, SocketAddr, Option<Vec<u8>>)>,
stop_manager: StopManager,
context: ChannelContext,
) -> anyhow::Result<WritableNotify> {
let poll = Poll::new()?;
let writable_notify = WritableNotify::new(Waker::new(poll.registry(), NOTIFY)?);
let worker = {
let writable_notify = writable_notify.clone();
stop_manager.add_listener("tcp_writable_handler".into(), move || {
if let Err(e) = writable_notify.stop() {
log::error!("{:?}", e);
}
})?
};
{
let writable_notify = writable_notify.clone();
thread::Builder::new()
.name("tcpWriteableListen".into())
.spawn(move || {
if let Err(e) = tcp_writable_listen(receiver, poll, writable_notify, &context) {
log::error!("{:?}", e);
}
worker.stop_all();
})?;
}
Ok(writable_notify)
}
/// 处理写事件
fn tcp_writable_listen(
receiver: Receiver<(TcpStream, Token, SocketAddr, Option<Vec<u8>>)>,
mut poll: Poll,
writable_notify: WritableNotify,
context: &ChannelContext,
) -> io::Result<()> {
let mut events = Events::with_capacity(1024);
let mut write_map: HashMap<
Token,
(
TcpStream,
SocketAddr,
Receiver<Vec<u8>>,
Option<(Vec<u8>, usize)>,
),
> = HashMap::with_capacity(32);
loop {
if let Err(e) = poll.poll(&mut events, None) {
crate::ignore_io_interrupted(e)?;
continue;
}
for event in events.iter() {
match event.token() {
NOTIFY => {
if writable_notify.is_stop() {
//服务停止
return Ok(());
}
if writable_notify.is_need_write() {
// 需要写入数据
if let Some(tokens) = writable_notify.take_all() {
for (token, state) in tokens {
if !state {
closed_handle_w(&token, &mut write_map, &context);
continue;
}
if let Err(e) = writable_handle(&token, &mut write_map) {
closed_handle_w(&token, &mut write_map, &context);
log::warn!("{:?}", e);
}
}
}
}
if writable_notify.is_add_socket() {
//添加tcp连接,并监听写事件
while let Ok((mut stream, token, addr, init_buf)) = receiver.try_recv() {
if let Err(e) = stream.set_nodelay(true) {
log::warn!("set_nodelay err={:?}", e);
}
if let Err(e) =
poll.registry()
.register(&mut stream, token, Interest::WRITABLE)
{
log::warn!("registry err={:?}", e);
continue;
}
let (sender, receiver) = sync_channel(128);
let packet_sender =
PacketSender::new(writable_notify.clone(), sender, token);
if let Some(init_buf) = init_buf {
packet_sender.try_send(&init_buf)?;
}
context.tcp_map.write().insert(addr, packet_sender);
write_map.insert(token, (stream, addr, receiver, None));
}
}
}
token => {
if event.is_writable() {
if let Err(e) = writable_handle(&token, &mut write_map) {
closed_handle_w(&token, &mut write_map, &context);
log::warn!("{:?}", e);
}
} else {
closed_handle_w(&token, &mut write_map, &context);
}
}
}
}
}
}
fn accept_handle(
pub async fn tcp_stream_handle<H>(
stream: TcpStream,
addr: SocketAddr,
init_buf: Option<Vec<u8>>,
write_waker: &WritableNotify,
read_map: &mut HashMap<Token, (RouteKey, TcpStream, Box<[u8; BUFFER_SIZE]>, usize)>,
tcp_sender: &SyncSender<(TcpStream, Token, SocketAddr, Option<Vec<u8>>)>,
registry: &Registry,
) -> io::Result<()> {
recv_handler: H,
context: ChannelContext,
) where
H: RecvChannelHandler,
{
let _ = stream.set_nodelay(true);
let local = stream.local_addr();
#[cfg(windows)]
let (tcp_stream, index) = unsafe {
let fd = stream.into_raw_socket();
(std::net::TcpStream::from_raw_socket(fd), fd as usize)
};
#[cfg(any(unix))]
let (tcp_stream, index) = unsafe {
let fd = stream.into_raw_fd();
(std::net::TcpStream::from_raw_fd(fd), fd as usize)
};
if index == 0 || index == 1 {
log::error!("index err={:?}", addr);
return Ok(());
}
let token = Token(index);
match tcp_stream.try_clone() {
Ok(tcp_writer) => {
match tcp_sender.try_send((TcpStream::from_std(tcp_writer), token, addr, init_buf)) {
Ok(_) => {
if let Err(e) = write_waker.add_socket() {
log::error!("write_waker,err={:?},addr={:?}", e, addr);
return Ok(());
}
}
Err(e) => {
return match e {
TrySendError::Full(_) => {
log::error!("Full,addr={:?}", addr);
Ok(())
}
TrySendError::Disconnected(_) => {
Err(io::Error::new(io::ErrorKind::Other, "write thread exit"))
}
};
}
let index = stream.as_raw_socket() as usize;
#[cfg(unix)]
let index = stream.as_raw_fd() as usize;
let route_key = RouteKey::new(ConnectProtocol::TCP, index, addr);
let (r, mut w) = stream.into_split();
let (sender, mut receiver) = channel::<Vec<u8>>(100);
context
.packet_map
.write()
.insert(route_key, PacketSender::new(sender));
tokio::spawn(async move {
while let Some(data) = receiver.recv().await {
if let Err(e) = tcp_write(&mut w, &data).await {
log::info!("发送失败,tcp链接终止:{:?},{:?}", addr, e);
break;
}
}
Err(e) => {
log::error!("try_clone err={:?},addr={:?}", e, addr);
return Ok(());
let _ = w.shutdown().await;
});
tokio::spawn(async move {
if let Err(e) = tcp_read(r, addr, &context, recv_handler, route_key).await {
log::warn!("tcp_read {:?} {local:?}-{addr}", e)
}
context.packet_map.write().remove(&route_key);
});
}
async fn tcp_write<W: AsyncWrite + Unpin>(w: &mut W, buf: &[u8]) -> anyhow::Result<()> {
let len = buf.len();
if len > TCP_MAX_PACKET_SIZE {
return Err(anyhow!("超过了tcp的最大长度传输"));
}
let mut stream = TcpStream::from_std(tcp_stream);
if let Err(e) = registry.register(&mut stream, token, Interest::READABLE) {
log::error!("registry err={:?},addr={:?}", e, addr);
return Ok(());
}
read_map.insert(
token,
(
RouteKey::new(true, index, addr),
stream,
Box::new([0; BUFFER_SIZE]),
0,
),
);
w.write_all(&[0, (len >> 16) as u8, (len >> 8) as u8, len as u8])
.await?;
w.write_all(&buf).await?;
Ok(())
}
fn readable_handle<H>(
token: &Token,
map: &mut HashMap<Token, (RouteKey, TcpStream, Box<[u8; BUFFER_SIZE]>, usize)>,
recv_handler: &mut H,
async fn tcp_read<H>(
mut read: OwnedReadHalf,
addr: SocketAddr,
context: &ChannelContext,
extend: &mut [u8],
) -> io::Result<()>
recv_handler: H,
route_key: RouteKey,
) -> anyhow::Result<()>
where
H: RecvChannelHandler,
{
if let Some((route_key, stream, buf, begin)) = map.get_mut(token) {
loop {
let end = if *begin >= 4 {
4 + (((buf[2] as u16) << 8) | buf[3] as u16) as usize
} else {
4
};
if end > BUFFER_SIZE {
return Err(io::Error::from(io::ErrorKind::InvalidData));
}
match stream.read(&mut buf[*begin..end]) {
Ok(len) => {
if len == 0 {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
}
*begin += len;
if end > 4 && *begin == end {
recv_handler.handle(&mut buf[4..end], extend, *route_key, context);
*begin = 0;
}
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
break;
}
return Err(e);
}
}
let mut head = [0; 4];
let mut buf = [0; BUFFER_SIZE];
let mut extend = [0; BUFFER_SIZE];
loop {
read.read_exact(&mut head).await?;
if head[0] != 0 {
return Err(anyhow!("tcp数据流错误 {}", addr));
}
}
Ok(())
}
fn writable_handle(
token: &Token,
map: &mut HashMap<
Token,
(
TcpStream,
SocketAddr,
Receiver<Vec<u8>>,
Option<(Vec<u8>, usize)>,
),
>,
) -> io::Result<()> {
if let Some((stream, _, receiver, last)) = map.get_mut(token) {
loop {
if let Some((buf, begin)) = last {
match stream.write(&buf[*begin..]) {
Ok(len) => {
if len == 0 {
return Err(io::Error::from(io::ErrorKind::WriteZero));
}
if len + *begin == buf.len() {
*last = None;
} else {
*begin += len;
continue;
}
}
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
break;
}
return Err(e);
}
}
}
match receiver.try_recv() {
Ok(buf) => *last = Some((buf, 0)),
Err(e) => match e {
TryRecvError::Empty => {
break;
}
TryRecvError::Disconnected => {
return Err(io::Error::from(io::ErrorKind::Other));
}
},
}
let len = ((head[1] as usize) << 16) | ((head[2] as usize) << 8) | head[3] as usize;
if len < 12 || len > buf.len() {
return Err(anyhow!("tcp数据长度无效 {}", addr));
}
}
Ok(())
}
fn closed_handle_r(
token: &Token,
map: &mut HashMap<Token, (RouteKey, TcpStream, Box<[u8; BUFFER_SIZE]>, usize)>,
) {
if let Some((_, tcp, _, _)) = map.remove(token) {
let _ = tcp.shutdown(Shutdown::Both);
}
}
fn closed_handle_w(
token: &Token,
map: &mut HashMap<
Token,
(
TcpStream,
SocketAddr,
Receiver<Vec<u8>>,
Option<(Vec<u8>, usize)>,
),
>,
context: &ChannelContext,
) {
if let Some((tcp, addr, _, _)) = map.remove(token) {
context.tcp_map.write().remove(&addr);
let _ = tcp.shutdown(Shutdown::Both);
read.read_exact(&mut buf[..len]).await?;
recv_handler.handle(&mut buf[..len], &mut extend, route_key, context);
}
}
+18 -13
View File
@@ -1,4 +1,3 @@
use std::collections::HashMap;
use std::sync::mpsc::{sync_channel, Receiver};
use std::{io, thread};
@@ -10,7 +9,7 @@ use crate::channel::context::ChannelContext;
use crate::channel::handler::RecvChannelHandler;
use crate::channel::notify::AcceptNotify;
use crate::channel::sender::AcceptSocketSender;
use crate::channel::{RouteKey, BUFFER_SIZE};
use crate::channel::{ConnectProtocol, RouteKey, BUFFER_SIZE};
use crate::util::StopManager;
pub fn udp_listen<H>(
@@ -60,7 +59,7 @@ where
fn sub_udp_listen0<H>(
mut poll: Poll,
mut recv_handler: H,
recv_handler: H,
context: ChannelContext,
accept_notify: AcceptNotify,
accept_receiver: Receiver<Option<Vec<UdpSocket>>>,
@@ -71,7 +70,8 @@ where
let mut events = Events::with_capacity(1024);
let mut buf = [0; BUFFER_SIZE];
let mut extend = [0; BUFFER_SIZE];
let mut read_map: HashMap<Token, UdpSocket> = HashMap::with_capacity(32);
let mut list: Vec<UdpSocket> = Vec::with_capacity(100);
let main_len = context.main_len();
loop {
if let Err(e) = poll.poll(&mut events, None) {
crate::ignore_io_interrupted(e)?;
@@ -88,39 +88,43 @@ where
match option {
None => {
log::info!("切换成锥形模式");
for (_, mut udp_socket) in read_map.drain() {
for mut udp_socket in list.drain(..) {
if let Err(e) = udp_socket.deregister(poll.registry()) {
log::error!("{:?}", e);
}
}
}
Some(socket_list) => {
for mut udp_socket in list.drain(..) {
if let Err(e) = udp_socket.deregister(poll.registry()) {
log::error!("deregister {:?}", e);
}
}
log::info!("切换成对称模式 监听端口数:{}", socket_list.len());
for (index, mut udp_socket) in
socket_list.into_iter().enumerate()
{
let token = Token(index + context.channel_num());
poll.registry().register(
&mut udp_socket,
token,
Token(index),
Interest::READABLE,
)?;
read_map.insert(token, udp_socket);
list.push(udp_socket);
}
}
}
}
}
}
token => {
if let Some(udp_socket) = read_map.get(&token) {
Token(index) => {
if let Some(udp_socket) = list.get(index) {
loop {
match udp_socket.recv_from(&mut buf) {
Ok((len, addr)) => {
recv_handler.handle(
&mut buf[..len],
&mut extend,
RouteKey::new(false, token.0, addr),
RouteKey::new(ConnectProtocol::UDP, index + main_len, addr),
&context,
);
}
@@ -238,7 +242,7 @@ where
pub fn main_udp_listen0<H>(
mut poll: Poll,
mut recv_handler: H,
recv_handler: H,
context: ChannelContext,
) -> io::Result<()>
where
@@ -266,6 +270,7 @@ where
for x in events.iter() {
let index = match x.token() {
NOTIFY => return Ok(()),
// 0的位置留给NOTIFY了,这里要再减回去,因为路由是通过index来找到对应udp的
Token(index) => index - 1,
};
let udp = if let Some(udp) = udps.get(index) {
@@ -280,7 +285,7 @@ where
recv_handler.handle(
&mut buf[..len],
&mut extend,
RouteKey::new(false, index, addr),
RouteKey::new(ConnectProtocol::UDP, index, addr),
&context,
);
}
+164
View File
@@ -0,0 +1,164 @@
use crate::channel::{ConnectProtocol, RouteKey, BUFFER_SIZE};
use anyhow::Context;
use futures_util::stream::SplitStream;
use futures_util::{SinkExt, StreamExt};
use std::convert::Into;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::thread;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::sync::mpsc::{channel, Receiver};
use tokio_tungstenite::tungstenite::http::StatusCode;
use tokio_tungstenite::tungstenite::{Error, Message};
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
use crate::channel::context::ChannelContext;
use crate::channel::handler::RecvChannelHandler;
use crate::channel::sender::PacketSender;
use crate::util::StopManager;
/// ws协议,
/// 暂时只允许用ws连服务端,不能用ws打洞/连客户端
pub fn ws_connect_accept<H>(
receiver: Receiver<(Vec<u8>, String)>,
recv_handler: H,
context: ChannelContext,
stop_manager: StopManager,
) -> anyhow::Result<()>
where
H: RecvChannelHandler,
{
let (stop_sender, stop_receiver) = tokio::sync::oneshot::channel::<()>();
let worker = stop_manager.add_listener("wsChannel".into(), move || {
let _ = stop_sender.send(());
})?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.context("ws tokio runtime build failed")?;
thread::Builder::new()
.name("wsChannel".into())
.spawn(move || {
runtime.spawn(async move { connect_ws_handle(receiver, recv_handler, context).await });
runtime.block_on(async {
let _ = stop_receiver.await;
});
runtime.shutdown_background();
worker.stop_all();
})
.context("ws thread build failed")?;
Ok(())
}
async fn connect_ws_handle<H>(
mut receiver: Receiver<(Vec<u8>, String)>,
recv_handler: H,
context: ChannelContext,
) where
H: RecvChannelHandler,
{
let mut index = 0;
while let Some((data, url)) = receiver.recv().await {
let recv_handler = recv_handler.clone();
let context = context.clone();
tokio::spawn(async move {
if let Err(e) = connect_ws(data, url, recv_handler, context, index).await {
log::warn!("发送失败,ws链接终止:{:?}", e);
}
});
index += 1;
}
}
const WS_ADDR: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0));
async fn connect_ws<H>(
data: Vec<u8>,
mut url: String,
recv_handler: H,
context: ChannelContext,
index: usize,
) -> anyhow::Result<()>
where
H: RecvChannelHandler,
{
let mut count = 0;
log::info!("尝试建立连接 {:?}", url);
let (mut ws, response) = loop {
count += 1;
if count > 3 {
Err(anyhow::anyhow!("发生多次重定向,链接终止"))?
}
match tokio::time::timeout(Duration::from_secs(3), connect_async(url)).await? {
Ok(rs) => break rs,
Err(e) => {
if let Error::Http(res) = &e {
if res.status() == StatusCode::MOVED_PERMANENTLY
|| res.status() == StatusCode::FOUND
|| res.status() == StatusCode::SEE_OTHER
|| res.status() == StatusCode::TEMPORARY_REDIRECT
|| res.status() == StatusCode::PERMANENT_REDIRECT
{
if let Some(v) = res.headers().get("Location") {
if let Ok(redirect) = v.to_str() {
log::info!("url重定向响应头 {:?}", res.headers());
log::info!("url重定向地址 {}", redirect);
url = redirect.to_string();
continue;
}
}
}
}
return Err(e)?;
}
}
};
log::info!("ws协议握手 {:?}", response);
ws.send(Message::Binary(data)).await?;
let (mut ws_write, ws_read) = ws.split();
let (sender, mut receiver) = channel::<Vec<u8>>(100);
let route_key = RouteKey::new(ConnectProtocol::WS, index, WS_ADDR);
context
.packet_map
.write()
.insert(route_key, PacketSender::new(sender));
tokio::spawn(async move {
while let Some(data) = receiver.recv().await {
if let Err(e) = ws_write.send(Message::Binary(data)).await {
log::warn!("websocket err {:?}", e);
break;
}
}
let _ = ws_write.close().await;
});
if let Err(e) = ws_read_handle(ws_read, recv_handler, &context, route_key).await {
log::warn!("{:?}", e);
}
context.packet_map.write().remove(&route_key);
Ok(())
}
async fn ws_read_handle<H>(
mut ws_read: SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>,
recv_handler: H,
context: &ChannelContext,
route_key: RouteKey,
) -> anyhow::Result<()>
where
H: RecvChannelHandler,
{
let mut extend = [0; BUFFER_SIZE];
while let Some(msg) = ws_read.next().await {
let msg = msg.context("Error during WebSocket ")?;
match msg {
Message::Text(txt) => log::info!("Received text message: {}", txt),
Message::Binary(mut data) => {
recv_handler.handle(&mut data, &mut extend, route_key, context);
}
Message::Ping(_) | Message::Pong(_) => (),
Message::Close(_) => break,
_ => {}
}
}
Ok(())
}
+124 -65
View File
@@ -1,5 +1,6 @@
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;
@@ -26,32 +27,20 @@ use crate::nat::NatTest;
#[cfg(feature = "integrated_tun")]
use crate::tun_tap_device::tun_create_helper::{DeviceAdapter, TunDeviceHelper};
use crate::tun_tap_device::vnt_device::DeviceWrite;
use crate::util::{
Scheduler, SingleU64Adder, StopManager, U64Adder, WatchSingleU64Adder, WatchU64Adder,
};
use crate::util::limit::TrafficMeterMultiAddress;
use crate::util::{Scheduler, StopManager};
use crate::{nat, VntCallback};
#[derive(Clone)]
pub struct Vnt {
stop_manager: StopManager,
config: Config,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
nat_test: NatTest,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
context: Arc<Mutex<Option<ChannelContext>>>,
peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>>,
down_count_watcher: WatchU64Adder,
up_count_watcher: WatchSingleU64Adder,
client_secret_hash: Option<[u8; 16]>,
compressor: Compressor,
client_cipher: Cipher,
external_route: ExternalRoute,
inner: Arc<VntInner>,
}
impl Vnt {
#[cfg(feature = "integrated_tun")]
pub fn new<Call: VntCallback>(config: Config, callback: Call) -> anyhow::Result<Self> {
Vnt::new_device0(config, callback, DeviceAdapter::default())
let inner = Arc::new(VntInner::new(config, callback)?);
Ok(Self { inner })
}
#[cfg(not(feature = "integrated_tun"))]
pub fn new_device<Call: VntCallback, Device: DeviceWrite>(
@@ -59,14 +48,64 @@ impl Vnt {
callback: Call,
device: Device,
) -> anyhow::Result<Self> {
Vnt::new_device0(config, callback, device)
let inner = Arc::new(VntInner::new_device(config, callback, device)?);
Ok(Self { inner })
}
}
impl Deref for Vnt {
type Target = VntInner;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
pub struct VntInner {
stop_manager: StopManager,
config: Config,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
nat_test: NatTest,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
context: Arc<Mutex<Option<ChannelContext>>>,
peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>>,
client_secret_hash: Option<[u8; 16]>,
compressor: Compressor,
client_cipher: Cipher,
server_cipher: Cipher,
external_route: ExternalRoute,
up_traffic_meter: Option<TrafficMeterMultiAddress>,
down_traffic_meter: Option<TrafficMeterMultiAddress>,
}
impl VntInner {
#[cfg(feature = "integrated_tun")]
pub fn new<Call: VntCallback>(config: Config, callback: Call) -> anyhow::Result<Self> {
VntInner::new_device0(config, callback, DeviceAdapter::default())
}
#[cfg(not(feature = "integrated_tun"))]
pub fn new_device<Call: VntCallback, Device: DeviceWrite>(
config: Config,
callback: Call,
device: Device,
) -> anyhow::Result<Self> {
VntInner::new_device0(config, callback, device)
}
fn new_device0<Call: VntCallback, Device: DeviceWrite>(
config: Config,
callback: Call,
device: Device,
) -> anyhow::Result<Self> {
log::info!("config.toml:{:?}", config);
log::info!("config: {:?}", config);
let (up_traffic_meter, down_traffic_meter) = if config.enable_traffic {
(
Some(TrafficMeterMultiAddress::default()),
Some(TrafficMeterMultiAddress::default()),
)
} else {
(None, None)
};
//服务端非对称加密
#[cfg(feature = "server_encrypt")]
let rsa_cipher: Arc<Mutex<Option<RsaCipher>>> = Arc::new(Mutex::new(None));
@@ -91,8 +130,15 @@ impl Vnt {
config.server_address,
)));
//设备列表
let device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>> =
Arc::new(Mutex::new((0, Vec::with_capacity(16))));
let device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>> =
Arc::new(Mutex::new((0, HashMap::with_capacity(16))));
let local_ipv4 = if let Some(local_ipv4) = config.local_ipv4 {
Some(local_ipv4)
} else {
nat::local_ipv4()
};
let default_interface = config.local_interface.clone();
//基础信息
let config_info = BaseConfigInfo::new(
config.name.clone(),
@@ -110,6 +156,8 @@ impl Vnt {
#[cfg(feature = "integrated_tun")]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
config.device_name.clone(),
config.allow_wire_guard,
default_interface.clone(),
);
// 服务停止管理器
let stop_manager = {
@@ -137,11 +185,13 @@ impl Vnt {
ports,
config.use_channel_type,
config.first_latency,
config.tcp,
config.protocol,
config.packet_loss_rate,
config.packet_delay,
default_interface,
up_traffic_meter.clone(),
down_traffic_meter.clone(),
)?;
let local_ipv4 = nat::local_ipv4();
let local_ipv6 = nat::local_ipv6();
let udp_ports = context.main_local_udp_port()?;
let tcp_port = tcp_listener.local_addr()?.port();
@@ -153,6 +203,8 @@ impl Vnt {
local_ipv6,
udp_ports,
tcp_port,
config.local_ipv4.is_none(),
config.punch_model,
);
// 定时器
let scheduler = Scheduler::new(stop_manager.clone())?;
@@ -174,15 +226,10 @@ impl Vnt {
let (punch_sender, punch_receiver) = maintain::punch_channel();
let peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>> =
Arc::new(RwLock::new(HashMap::with_capacity(16)));
let down_counter =
U64Adder::with_capacity(config.ports.as_ref().map(|v| v.len()).unwrap_or_default() + 8);
let down_count_watcher = down_counter.watch();
let handshake = Handshake::new(
#[cfg(feature = "server_encrypt")]
rsa_cipher.clone(),
);
let up_counter = SingleU64Adder::new();
let up_count_watcher = up_counter.watch();
#[cfg(feature = "integrated_tun")]
let tun_device_helper = {
TunDeviceHelper::new(
@@ -194,8 +241,7 @@ impl Vnt {
proxy_map.clone(),
client_cipher.clone(),
server_cipher.clone(),
up_counter,
device_list.clone(),
device_map.clone(),
config.compressor,
device.clone().into_device_adapter(),
)
@@ -208,7 +254,7 @@ impl Vnt {
client_cipher.clone(),
current_device.clone(),
device,
device_list.clone(),
device_map.clone(),
config_info.clone(),
nat_test.clone(),
callback.clone(),
@@ -219,23 +265,21 @@ impl Vnt {
#[cfg(feature = "ip_proxy")]
#[cfg(feature = "integrated_tun")]
proxy_map.clone(),
down_counter,
handshake.clone(),
#[cfg(feature = "integrated_tun")]
tun_device_helper,
);
//初始化网络数据通道
let (udp_socket_sender, tcp_socket_sender) =
let (udp_socket_sender, connect_util) =
init_channel(tcp_listener, context.clone(), stop_manager.clone(), handler)?;
// 打洞逻辑
let punch = Punch::new(
context.clone(),
config.punch_model,
config.tcp,
tcp_socket_sender.clone(),
external_route.clone(),
connect_util.clone(),
nat_test.clone(),
current_device.clone(),
);
// #[cfg(not(target_os = "android"))]
@@ -246,7 +290,7 @@ impl Vnt {
context.clone(),
current_device.clone(),
config_info.clone(),
tcp_socket_sender.clone(),
connect_util.clone(),
callback.clone(),
0,
handshake,
@@ -254,9 +298,7 @@ impl Vnt {
{
let context = context.clone();
let nat_test = nat_test.clone();
let device_list = device_list.clone();
let down_count_watcher = down_count_watcher.clone();
let up_count_watcher = up_count_watcher.clone();
let device_map = device_map.clone();
let config_info = config_info.clone();
let current_device = current_device.clone();
if !config.use_channel_type.is_only_relay() {
@@ -269,13 +311,14 @@ impl Vnt {
);
}
let client_cipher = client_cipher.clone();
let server_cipher = server_cipher.clone();
//延迟启动
scheduler.timeout(Duration::from_secs(3), move |scheduler| {
start(
scheduler,
context,
nat_test,
device_list,
device_map,
current_device,
client_cipher,
server_cipher,
@@ -283,8 +326,6 @@ impl Vnt {
config_info,
punch,
callback,
down_count_watcher,
up_count_watcher,
);
});
}
@@ -294,15 +335,16 @@ impl Vnt {
config,
current_device,
nat_test,
device_list,
device_map,
context: Arc::new(Mutex::new(Some(context))),
peer_nat_info_map,
down_count_watcher,
up_count_watcher,
client_secret_hash: config_info.client_secret_hash,
compressor,
client_cipher,
server_cipher,
external_route,
up_traffic_meter,
down_traffic_meter,
})
}
}
@@ -311,7 +353,7 @@ pub fn start<Call: VntCallback>(
scheduler: &Scheduler,
context: ChannelContext,
nat_test: NatTest,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
client_cipher: Cipher,
server_cipher: Cipher,
@@ -319,15 +361,13 @@ pub fn start<Call: VntCallback>(
config_info: BaseConfigInfo,
punch: Punch,
callback: Call,
down_count_watcher: WatchU64Adder,
up_count_watcher: WatchSingleU64Adder,
) {
// 定时心跳
maintain::heartbeat(
&scheduler,
context.clone(),
current_device.clone(),
device_list.clone(),
device_map.clone(),
client_cipher.clone(),
server_cipher.clone(),
);
@@ -347,7 +387,7 @@ pub fn start<Call: VntCallback>(
&scheduler,
context.clone(),
current_device.clone(),
device_list.clone(),
device_map.clone(),
client_cipher.clone(),
);
}
@@ -358,7 +398,6 @@ pub fn start<Call: VntCallback>(
&scheduler,
context.clone(),
current_device.clone(),
server_cipher.clone(),
nat_test.clone(),
config_info.clone(),
);
@@ -367,23 +406,17 @@ pub fn start<Call: VntCallback>(
&scheduler,
context.clone(),
nat_test.clone(),
device_list.clone(),
device_map.clone(),
current_device.clone(),
client_cipher.clone(),
punch_receiver,
punch,
);
}
maintain::up_status(
scheduler,
context.clone(),
current_device.clone(),
down_count_watcher,
up_count_watcher,
)
maintain::up_status(scheduler, context.clone(), current_device.clone())
}
impl Vnt {
impl VntInner {
pub fn name(&self) -> &str {
&self.config.name
}
@@ -412,10 +445,10 @@ impl Vnt {
self.nat_test.nat_info()
}
pub fn device_list(&self) -> Vec<PeerDeviceInfo> {
let device_list_lock = self.device_list.lock();
let device_list_lock = self.device_map.lock();
let (_epoch, device_list) = device_list_lock.clone();
drop(device_list_lock);
device_list
device_list.into_values().collect()
}
pub fn route(&self, ip: &Ipv4Addr) -> Option<Route> {
self.context.lock().as_ref()?.route_table.route_one(ip)
@@ -438,16 +471,33 @@ impl Vnt {
}
}
pub fn up_stream(&self) -> u64 {
self.up_count_watcher.get()
self.up_traffic_meter.as_ref().map_or(0, |v| v.total())
}
pub fn up_stream_all(&self) -> Option<(u64, HashMap<Ipv4Addr, u64>)> {
self.up_traffic_meter.as_ref().map(|v| v.get_all())
}
pub fn up_stream_history(&self) -> Option<(u64, HashMap<Ipv4Addr, (u64, Vec<usize>)>)> {
self.up_traffic_meter.as_ref().map(|v| v.get_all_history())
}
pub fn down_stream(&self) -> u64 {
self.down_count_watcher.get()
self.down_traffic_meter.as_ref().map_or(0, |v| v.total())
}
pub fn down_stream_all(&self) -> Option<(u64, HashMap<Ipv4Addr, u64>)> {
self.down_traffic_meter.as_ref().map(|v| v.get_all())
}
pub fn down_stream_history(&self) -> Option<(u64, HashMap<Ipv4Addr, (u64, Vec<usize>)>)> {
self.down_traffic_meter
.as_ref()
.map(|v| v.get_all_history())
}
pub fn stop(&self) {
//退出协助回收资源
let _ = self.context.lock().take();
self.stop_manager.stop()
}
pub fn is_stopped(&self) -> bool {
self.stop_manager.is_stopped()
}
pub fn add_stop_listener<F>(&self, name: String, f: F) -> anyhow::Result<crate::util::Worker>
where
F: FnOnce() + Send + 'static,
@@ -470,10 +520,19 @@ impl Vnt {
self.current_device.clone(),
self.compressor.clone(),
self.client_cipher.clone(),
self.server_cipher.clone(),
self.external_route.clone(),
self.device_map.clone(),
self.config.allow_wire_guard,
))
} else {
None
}
}
}
impl Drop for VntInner {
fn drop(&mut self) {
self.stop();
}
}
+62 -6
View File
@@ -5,7 +5,8 @@ use std::str::FromStr;
pub use conn::Vnt;
use crate::channel::punch::PunchModel;
use crate::channel::UseChannelType;
use crate::channel::socket::LocalInterface;
use crate::channel::{ConnectProtocol, UseChannelType};
use crate::cipher::CipherModel;
use crate::compression::Compressor;
use crate::util::{address_choose, dns_query_all};
@@ -28,7 +29,7 @@ pub struct Config {
pub out_ips: Vec<(u32, u32)>,
pub password: Option<String>,
pub mtu: Option<u32>,
pub tcp: bool,
pub protocol: ConnectProtocol,
pub ip: Option<Ipv4Addr>,
#[cfg(feature = "ip_proxy")]
#[cfg(feature = "integrated_tun")]
@@ -50,6 +51,10 @@ pub struct Config {
#[cfg(feature = "port_mapping")]
pub port_mapping_list: Vec<(bool, SocketAddr, String)>,
pub compressor: Compressor,
pub enable_traffic: bool,
pub allow_wire_guard: bool,
pub local_ipv4: Option<Ipv4Addr>,
pub local_interface: LocalInterface,
}
impl Config {
@@ -67,7 +72,6 @@ impl Config {
out_ips: Vec<(u32, u32)>,
password: Option<String>,
mtu: Option<u32>,
tcp: bool,
ip: Option<Ipv4Addr>,
#[cfg(feature = "integrated_tun")]
#[cfg(feature = "ip_proxy")]
@@ -87,7 +91,20 @@ impl Config {
// 例如 [udp:127.0.0.1:80->10.26.0.10:8080,tcp:127.0.0.1:80->10.26.0.10:8080]
#[cfg(feature = "port_mapping")] port_mapping_list: Vec<String>,
compressor: Compressor,
enable_traffic: bool,
// 允许传递wg流量
allow_wire_guard: bool,
local_dev: Option<String>,
) -> anyhow::Result<Self> {
#[cfg(windows)]
#[cfg(feature = "integrated_tun")]
if !tap {
if let Err(e) = tun::Device::check_tun_dll() {
log::warn!("校验平台dll {:?}", e);
Err(e)?;
}
}
for x in stun_server.iter_mut() {
if !x.contains(":") {
x.push_str(":3478");
@@ -109,8 +126,36 @@ impl Config {
if name.is_empty() || name.len() > 128 {
return Err(anyhow!("name too long"));
}
let server_address =
address_choose(dns_query_all(&server_address_str, name_servers.clone())?)?;
let mut server_address_str = server_address_str.to_lowercase();
let mut _query_dns = true;
let mut protocol = ConnectProtocol::UDP;
if server_address_str.starts_with("ws://") {
#[cfg(not(feature = "ws"))]
Err(anyhow!("Ws not supported"))?;
protocol = ConnectProtocol::WS;
_query_dns = false;
}
if server_address_str.starts_with("wss://") {
#[cfg(not(feature = "wss"))]
Err(anyhow!("Wss not supported"))?;
protocol = ConnectProtocol::WSS;
_query_dns = false;
}
let mut server_address = "0.0.0.0:0".parse().unwrap();
if _query_dns {
if let Some(s) = server_address_str.strip_prefix("udp://") {
server_address_str = s.to_string();
} else if let Some(s) = server_address_str.strip_prefix("tcp://") {
server_address_str = s.to_string();
protocol = ConnectProtocol::TCP;
}
server_address = address_choose(dns_query_all(
&server_address_str,
name_servers.clone(),
&LocalInterface::default(),
)?)?;
}
#[cfg(feature = "port_mapping")]
let port_mapping_list = crate::port_mapping::convert(port_mapping_list)?;
@@ -118,6 +163,13 @@ impl Config {
*dest = *mask & *dest;
}
in_ips.sort_by(|(dest1, _, _), (dest2, _, _)| dest2.cmp(dest1));
let (local_interface, local_ipv4) = if let Some(local_dev) = local_dev {
let (default_interface, ip) = crate::channel::socket::get_interface(local_dev)?;
log::info!("default_interface = {:?} local_ip= {ip}", default_interface);
(default_interface, Some(ip))
} else {
(LocalInterface::default(), None)
};
Ok(Self {
#[cfg(feature = "integrated_tun")]
#[cfg(target_os = "windows")]
@@ -133,7 +185,7 @@ impl Config {
out_ips,
password,
mtu,
tcp,
protocol,
ip,
#[cfg(feature = "ip_proxy")]
#[cfg(feature = "integrated_tun")]
@@ -153,6 +205,10 @@ impl Config {
#[cfg(feature = "port_mapping")]
port_mapping_list,
compressor,
enable_traffic,
allow_wire_guard,
local_ipv4,
local_interface,
})
}
}
+4
View File
@@ -172,6 +172,8 @@ pub enum ErrorType {
IpAlreadyExists,
InvalidIp,
LocalIpExists,
FailedToCrateDevice,
Warn,
Unknown,
}
@@ -184,6 +186,8 @@ impl Into<u8> for ErrorType {
ErrorType::IpAlreadyExists => 4,
ErrorType::InvalidIp => 5,
ErrorType::LocalIpExists => 6,
ErrorType::FailedToCrateDevice => 101,
ErrorType::Warn => 102,
ErrorType::Unknown => 255,
}
}
+6 -2
View File
@@ -30,7 +30,11 @@ impl Handshake {
#[cfg(feature = "server_encrypt")] rsa_cipher: Arc<Mutex<Option<RsaCipher>>>,
) -> Self {
Handshake {
time: Arc::new(AtomicCell::new(Instant::now() - Duration::from_secs(60))),
time: Arc::new(AtomicCell::new(
Instant::now()
.checked_sub(Duration::from_secs(60))
.unwrap_or(Instant::now()),
)),
#[cfg(feature = "server_encrypt")]
rsa_cipher,
}
@@ -43,7 +47,7 @@ impl Handshake {
}
let request_packet = self.handshake_request_packet(secret)?;
log::info!("发送握手请求,secret={},{:?}", secret, addr);
context.send_default(request_packet.buffer(), addr)?;
context.send_default(&request_packet, addr)?;
self.time.store(Instant::now());
Ok(())
}
+17 -53
View File
@@ -5,68 +5,50 @@ use crossbeam_utils::atomic::AtomicCell;
use crate::channel::context::ChannelContext;
use crate::channel::punch::NatType;
use crate::cipher::Cipher;
use crate::handle::{BaseConfigInfo, CurrentDeviceInfo};
use crate::nat::NatTest;
use crate::protocol::body::ENCRYPTION_RESERVED;
use crate::protocol::{control_packet, NetPacket, Protocol, MAX_TTL};
use crate::util::Scheduler;
pub fn addr_request(
scheduler: &Scheduler,
context: ChannelContext,
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
server_cipher: Cipher,
nat_test: NatTest,
_config: BaseConfigInfo,
) {
pub_address_request(
scheduler,
context,
current_device_info.clone(),
server_cipher,
nat_test,
0,
);
pub_address_request(scheduler, context, current_device_info.clone(), nat_test, 0);
}
fn pub_address_request(
scheduler: &Scheduler,
context: ChannelContext,
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
server_cipher: Cipher,
nat_test: NatTest,
count: usize,
) {
let channel_num = context.channel_num();
let index = count % channel_num;
let mut time = if index == channel_num - 1 { 19 } else { 1 };
if let Err(e) = addr_request0(
&context,
&current_device_info,
&server_cipher,
&nat_test,
index,
) {
if let Err(e) = addr_request0(&context, &current_device_info, &nat_test, index) {
log::warn!("{:?}", e);
}
let nat_info = nat_test.nat_info();
if nat_info.nat_type == NatType::Symmetric {
let time = if !nat_info.public_ports.contains(&0) && !nat_info.public_ips.is_empty() {
//对称网络探测端口没啥作用,把频率放低,(锥形网络也只在打洞前需要探测端口,后续可以改改)
if !nat_info.public_ports.contains(&0) && !nat_info.public_ips.is_empty() {
time = 600;
if nat_info.nat_type == NatType::Symmetric {
600
} else {
if index == channel_num - 1 {
19
} else {
9
}
}
}
} else {
3
};
let rs = scheduler.timeout(Duration::from_secs(time), move |s| {
pub_address_request(
s,
context,
current_device_info,
server_cipher,
nat_test,
index + 1,
)
pub_address_request(s, context, current_device_info, nat_test, index + 1)
});
if !rs {
log::info!("定时任务停止");
@@ -76,7 +58,6 @@ fn pub_address_request(
fn addr_request0(
context: &ChannelContext,
current_device: &AtomicCell<CurrentDeviceInfo>,
server_cipher: &Cipher,
nat_test: &NatTest,
index: usize,
) -> anyhow::Result<()> {
@@ -84,24 +65,7 @@ fn addr_request0(
if current_dev.status.offline() {
return Ok(());
}
if current_dev.connect_server.is_ipv4() && !context.is_main_tcp() {
// 如果连接的是ipv4服务,则探测公网端口
let gateway_ip = current_dev.virtual_gateway;
let src_ip = current_dev.virtual_ip;
let mut packet = NetPacket::new_encrypt([0; 12 + ENCRYPTION_RESERVED]).unwrap();
packet.set_default_version();
packet.set_gateway_flag(true);
packet.set_protocol(Protocol::Control);
packet.set_transport_protocol(control_packet::Protocol::AddrRequest.into());
packet.first_set_ttl(MAX_TTL);
packet.set_source(src_ip);
packet.set_destination(gateway_ip);
server_cipher.encrypt_ipv4(&mut packet)?;
context.send_main_udp(index, packet.buffer(), current_dev.connect_server)?;
} else {
let (data, addr) = nat_test.send_data()?;
context.send_main_udp(index, &data, addr)?;
}
let (data, addr) = nat_test.send_data()?;
context.send_main_udp(index, &data, addr)?;
Ok(())
}
+39 -27
View File
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::Arc;
use std::time::Duration;
@@ -19,14 +20,14 @@ pub fn heartbeat(
scheduler: &Scheduler,
context: ChannelContext,
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
client_cipher: Cipher,
server_cipher: Cipher,
) {
heartbeat0(
&context,
&current_device_info.load(),
&device_list,
&device_map,
&client_cipher,
&server_cipher,
);
@@ -36,7 +37,7 @@ pub fn heartbeat(
s,
context,
current_device_info,
device_list,
device_map,
client_cipher,
server_cipher,
)
@@ -49,18 +50,18 @@ pub fn heartbeat(
fn heartbeat0(
context: &ChannelContext,
current_device: &CurrentDeviceInfo,
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
device_map: &Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>,
client_cipher: &Cipher,
server_cipher: &Cipher,
) {
let gateway_ip = current_device.virtual_gateway;
let src_ip = current_device.virtual_ip;
let channel_num = context.channel_num();
// 可能服务器ip发生变化,导致发送失败
let mut is_send_gateway = false;
match heartbeat_packet_server(device_list, server_cipher, src_ip, gateway_ip) {
match heartbeat_packet_server(device_map, server_cipher, src_ip, gateway_ip) {
Ok(net_packet) => {
if let Err(e) = context.send_default(net_packet.buffer(), current_device.connect_server)
{
if let Err(e) = context.send_default(&net_packet, current_device.connect_server) {
log::warn!("heartbeat err={:?}", e)
} else {
is_send_gateway = true
@@ -76,7 +77,7 @@ fn heartbeat0(
if is_send_gateway {
continue;
}
heartbeat_packet_server(device_list, server_cipher, src_ip, gateway_ip)
heartbeat_packet_server(device_map, server_cipher, src_ip, gateway_ip)
} else {
heartbeat_packet_client(client_cipher, src_ip, dest_ip)
};
@@ -87,15 +88,24 @@ fn heartbeat0(
continue;
}
};
for route in routes {
if let Err(e) = context.send_by_key(net_packet.buffer(), route.route_key()) {
for (index, route) in routes.iter().enumerate() {
let limit = if context.first_latency() {
channel_num + 1
} else {
channel_num
};
if index >= limit {
// 多余的通道不再发送心跳包,让它自动过期
break;
}
if let Err(e) = context.send_by_key(&net_packet, route.route_key()) {
log::warn!("heartbeat err={:?}", e)
}
}
}
let peer_list = { device_list.lock().1.clone() };
for peer in &peer_list {
if !peer.status.is_online() {
let peer_list = { device_map.lock().1.clone() };
for peer in peer_list.values() {
if !peer.status.is_online() || peer.wireguard {
continue;
}
if current_device.is_gateway(&peer.virtual_ip) {
@@ -113,8 +123,7 @@ fn heartbeat0(
continue;
}
};
if let Err(e) = context.send_default(net_packet.buffer(), current_device.connect_server)
{
if let Err(e) = context.send_default(&net_packet, current_device.connect_server) {
log::error!("heartbeat_packet send_default err={:?}", e);
}
}
@@ -126,11 +135,11 @@ pub fn client_relay(
scheduler: &Scheduler,
context: ChannelContext,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
client_cipher: Cipher,
) {
let rs = scheduler.timeout(Duration::from_secs(30), move |s| {
client_relay_(s, context, current_device, device_list, client_cipher)
client_relay_(s, context, current_device, device_map, client_cipher)
});
if !rs {
log::info!("定时任务停止");
@@ -142,19 +151,19 @@ fn client_relay_(
scheduler: &Scheduler,
context: ChannelContext,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
client_cipher: Cipher,
) {
if let Err(e) = client_relay0(
&context,
&current_device.load(),
&device_list,
&device_map,
&client_cipher,
) {
log::error!("{:?}", e);
}
let rs = scheduler.timeout(Duration::from_secs(30), move |s| {
client_relay_(s, context, current_device, device_list, client_cipher)
client_relay_(s, context, current_device, device_map, client_cipher)
});
if !rs {
log::info!("定时任务停止");
@@ -164,17 +173,20 @@ fn client_relay_(
fn client_relay0(
context: &ChannelContext,
current_device: &CurrentDeviceInfo,
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
device_map: &Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>,
client_cipher: &Cipher,
) -> anyhow::Result<()> {
// 离线了不再探测
if current_device.status.offline() {
return Ok(());
}
let peer_list = { device_list.lock().1.clone() };
let peer_list = { device_map.lock().1.clone() };
let mut routes = context.route_table.route_table_p2p();
for peer in &peer_list {
if !peer.status.is_online() || peer.virtual_ip == current_device.virtual_ip {
for peer in peer_list.values() {
if peer.wireguard
|| !peer.status.is_online()
|| peer.virtual_ip == current_device.virtual_ip
{
continue;
}
if context
@@ -195,7 +207,7 @@ fn client_relay0(
if current_device.is_gateway(ip) {
continue;
}
if let Err(e) = context.send_by_key(client_packet.buffer(), route.route_key()) {
if let Err(e) = context.send_by_key(&client_packet, route.route_key()) {
log::error!("{:?}", e);
}
if index >= 2 {
@@ -234,14 +246,14 @@ fn heartbeat_packet_client(
}
fn heartbeat_packet_server(
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
device_map: &Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>,
server_cipher: &Cipher,
src: Ipv4Addr,
dest: Ipv4Addr,
) -> anyhow::Result<NetPacket<[u8; 12 + 4 + ENCRYPTION_RESERVED]>> {
let mut net_packet = heartbeat_packet(src, dest)?;
let mut ping = PingPacket::new(net_packet.payload_mut())?;
ping.set_epoch(device_list.lock().0);
ping.set_epoch(device_map.lock().0);
net_packet.set_gateway_flag(true);
server_cipher.encrypt_ipv4(&mut net_packet)?;
Ok(net_packet)
+33 -26
View File
@@ -1,14 +1,14 @@
use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use crossbeam_utils::atomic::AtomicCell;
use mio::net::TcpStream;
use crate::channel::context::ChannelContext;
use crate::channel::idle::{Idle, IdleType};
use crate::channel::sender::AcceptSocketSender;
use crate::channel::sender::ConnectUtil;
use crate::channel::socket::LocalInterface;
use crate::channel::ConnectProtocol;
use crate::handle::callback::{ConnectInfo, ErrorType};
use crate::handle::handshaker::Handshake;
use crate::handle::{BaseConfigInfo, ConnectStatus, CurrentDeviceInfo};
@@ -36,7 +36,7 @@ pub fn idle_gateway<Call: VntCallback>(
context: ChannelContext,
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
config: BaseConfigInfo,
tcp_socket_sender: AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>,
connect_util: ConnectUtil,
call: Call,
mut connect_count: usize,
handshake: Handshake,
@@ -45,7 +45,7 @@ pub fn idle_gateway<Call: VntCallback>(
&context,
&current_device_info,
&config,
&tcp_socket_sender,
&connect_util,
&call,
&mut connect_count,
&handshake,
@@ -56,7 +56,7 @@ pub fn idle_gateway<Call: VntCallback>(
context,
current_device_info,
config,
tcp_socket_sender,
connect_util,
call,
connect_count,
handshake,
@@ -71,7 +71,7 @@ fn idle_gateway0<Call: VntCallback>(
context: &ChannelContext,
current_device: &AtomicCell<CurrentDeviceInfo>,
config: &BaseConfigInfo,
tcp_socket_sender: &AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>,
connect_util: &ConnectUtil,
call: &Call,
connect_count: &mut usize,
handshake: &Handshake,
@@ -80,7 +80,7 @@ fn idle_gateway0<Call: VntCallback>(
context,
current_device,
config,
tcp_socket_sender,
connect_util,
call,
connect_count,
handshake,
@@ -120,7 +120,7 @@ fn check_gateway_channel<Call: VntCallback>(
context: &ChannelContext,
current_device_info: &AtomicCell<CurrentDeviceInfo>,
config: &BaseConfigInfo,
tcp_socket_sender: &AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>,
connect_util: &ConnectUtil,
call: &Call,
count: &mut usize,
handshake: &Handshake,
@@ -128,28 +128,30 @@ fn check_gateway_channel<Call: VntCallback>(
let mut current_device = current_device_info.load();
if current_device.status.offline() {
*count += 1;
// 探测服务器地址
current_device = domain_request0(current_device_info, config);
let connect_protocol = context.main_protocol();
if connect_protocol.is_transport() {
// 传输层的协议需要探测服务器地址
current_device =
domain_request0(current_device_info, config, context.default_interface());
}
//需要重连
call.connect(ConnectInfo::new(*count, current_device.connect_server));
log::info!("发送握手请求,{:?}", config);
if let Err(e) = handshake.send(context, config.server_secret, current_device.connect_server)
{
log::warn!("{:?}", e);
if context.is_main_tcp() {
let request_packet = handshake.handshake_request_packet(config.server_secret)?;
//tcp需要重连
let tcp_stream = std::net::TcpStream::connect_timeout(
&current_device.connect_server,
Duration::from_secs(5),
)?;
tcp_stream.set_nonblocking(true)?;
if let Err(e) = tcp_socket_sender.try_add_socket((
TcpStream::from_std(tcp_stream),
current_device.connect_server,
Some(request_packet.into_buffer()),
)) {
log::warn!("{:?}", e)
let request_packet = handshake.handshake_request_packet(config.server_secret)?;
match connect_protocol {
ConnectProtocol::UDP => {}
ConnectProtocol::TCP => {
connect_util.try_connect_tcp(
request_packet.into_buffer(),
current_device.connect_server,
);
}
ConnectProtocol::WS | ConnectProtocol::WSS => {
connect_util
.try_connect_ws(request_packet.into_buffer(), config.server_addr.clone());
}
}
}
@@ -160,11 +162,16 @@ fn check_gateway_channel<Call: VntCallback>(
pub fn domain_request0(
current_device: &AtomicCell<CurrentDeviceInfo>,
config: &BaseConfigInfo,
default_interface: &LocalInterface,
) -> CurrentDeviceInfo {
let mut current_dev = current_device.load();
// 探测服务端地址变化
match dns_query_all(&config.server_addr, config.name_servers.clone()) {
match dns_query_all(
&config.server_addr,
config.name_servers.clone(),
default_interface,
) {
Ok(addrs) => {
log::info!(
"domain {} dns {:?} addr {:?}",
+48 -29
View File
@@ -1,5 +1,6 @@
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::ops::{Div, Mul};
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
use std::sync::Arc;
use std::thread;
@@ -89,7 +90,7 @@ pub fn punch(
scheduler: &Scheduler,
context: ChannelContext,
nat_test: NatTest,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
client_cipher: Cipher,
receiver: PunchReceiver,
@@ -101,7 +102,7 @@ pub fn punch(
scheduler,
context,
nat_test,
device_list,
device_map,
current_device.clone(),
client_cipher.clone(),
0,
@@ -148,7 +149,7 @@ fn punch_start(
*v += 1;
*v
} else {
guard.insert(peer_ip, 1);
guard.insert(peer_ip, 0);
0
}
};
@@ -158,7 +159,7 @@ fn punch_start(
log::error!("{:?}", e);
continue;
}
if let Err(e) = punch.punch(packet.buffer(), peer_ip, nat_info, count < 2) {
if let Err(e) = punch.punch(packet.buffer(), peer_ip, nat_info, count < 2, count) {
log::warn!("{:?}", e)
}
}
@@ -169,19 +170,19 @@ fn punch_request(
scheduler: &Scheduler,
context: ChannelContext,
nat_test: NatTest,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
client_cipher: Cipher,
count: usize,
punch_record: Arc<Mutex<HashMap<Ipv4Addr, usize>>>,
mut last_punch_record: HashMap<Ipv4Addr, usize>,
mut last_punch_record: HashMap<Ipv4Addr, PunchRecordItem>,
) {
let curr = current_device.load();
let secs = if curr.status.online() {
if let Err(e) = punch0(
&context,
&nat_test,
&device_list,
&device_map,
curr,
&client_cipher,
&punch_record,
@@ -190,7 +191,7 @@ fn punch_request(
) {
log::warn!("{:?}", e)
}
let sleep_time = [5, 6, 7];
let sleep_time = [6, 7];
Duration::from_secs(sleep_time[count % sleep_time.len()])
} else {
Duration::from_secs(5)
@@ -200,7 +201,7 @@ fn punch_request(
s,
context,
nat_test,
device_list,
device_map,
current_device,
client_cipher,
count + 1,
@@ -212,16 +213,21 @@ fn punch_request(
log::info!("定时任务停止");
}
}
#[derive(Copy, Clone, Default)]
struct PunchRecordItem {
pub punch_record: usize,
pub last_p2p_num: usize,
}
/// 随机对需要打洞的客户端发起打洞请求
fn punch0(
context: &ChannelContext,
nat_test: &NatTest,
device_list: &Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: &Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
current_device: CurrentDeviceInfo,
client_cipher: &Cipher,
punch_record: &Mutex<HashMap<Ipv4Addr, usize>>,
last_punch_record: &mut HashMap<Ipv4Addr, usize>,
last_punch_record: &mut HashMap<Ipv4Addr, PunchRecordItem>,
total_count: usize,
) -> anyhow::Result<()> {
let nat_info = nat_test.nat_info();
@@ -232,33 +238,39 @@ fn punch0(
|| nat_info.public_ports.iter().filter(|&&v| v == 0).count()
> nat_info.public_ports.len() / 2)
{
log::info!("公网地址为空,暂时放弃打洞,第{}轮", total_count);
log::info!("未获取到公网地址,暂时放弃打洞,第{}轮", total_count);
return Ok(());
}
let current_ip = current_device.virtual_ip;
let mut list: Vec<PeerDeviceInfo> = device_list
let mut list: Vec<PeerDeviceInfo> = device_map
.lock()
.1
.iter()
.filter(|info| info.status.is_online() && info.virtual_ip > current_ip)
.values()
.filter(|info| !info.wireguard && info.virtual_ip > current_ip)
.cloned()
.collect();
list.shuffle(&mut rand::thread_rng());
for info in list {
let punch_count = punch_record
if info.status.is_offline() {
// 客户端掉线了要重置打洞记录
punch_record.lock().remove(&info.virtual_ip);
continue;
}
let mut punch_count = punch_record
.lock()
.get(&info.virtual_ip)
.cloned()
.unwrap_or(0);
.unwrap_or(0)
.mul(2)
.div(3);
let p2p_num = context.route_table.p2p_num(&info.virtual_ip);
let mut max_punch_interval = 70;
let mut max_punch_interval = 50;
if p2p_num > 0 {
if punch_count == 0 {
continue;
}
if p2p_num >= context.channel_num() {
//通道数满足要求,不再打洞
punch_record.lock().remove(&info.virtual_ip);
if punch_count != 0 {
punch_record.lock().remove(&info.virtual_ip);
}
continue;
}
//有p2p通道,但是通道数量不够,则继续打洞
@@ -266,13 +278,18 @@ fn punch0(
max_punch_interval = 300;
}
// 能发起打洞的前提是自己空闲,这里会间隔5秒以上发起一次打洞,所以假定上一轮打洞已结束
let last_punch = last_punch_record
.get(&info.virtual_ip)
.cloned()
.unwrap_or(0);
let last_punch = last_punch_record.entry(info.virtual_ip).or_default();
if last_punch.last_p2p_num > p2p_num {
// 打的洞掉线了,需要重置重新打
punch_record.lock().remove(&info.virtual_ip);
punch_count = 0;
}
// 梯度增加打洞时间间隔
if total_count > last_punch + punch_count.min(max_punch_interval) {
last_punch_record.insert(info.virtual_ip, total_count);
if total_count > last_punch.punch_record + punch_count.min(max_punch_interval) {
// 记录打洞周期,抑制下一次打洞,从而递减打洞频率
last_punch.punch_record = total_count;
last_punch.last_p2p_num = p2p_num;
let packet = punch_packet(
client_cipher,
current_device.virtual_ip(),
@@ -286,7 +303,7 @@ fn punch0(
punch_count,
total_count,
);
context.send_default(packet.buffer(), current_device.connect_server)?;
context.send_default(&packet, current_device.connect_server)?;
break;
}
}
@@ -309,6 +326,7 @@ fn punch_packet(
punch_reply.public_port = nat_info.public_ports.get(0).map_or(0, |v| *v as u32);
punch_reply.public_ports = nat_info.public_ports.iter().map(|e| *e as u32).collect();
punch_reply.public_port_range = nat_info.public_port_range as u32;
punch_reply.public_tcp_port = nat_info.public_tcp_port as u32;
punch_reply.local_ip = u32::from(nat_info.local_ipv4().unwrap_or(Ipv4Addr::UNSPECIFIED));
punch_reply.local_port = nat_info.udp_ports[0] as u32;
punch_reply.tcp_port = nat_info.tcp_port as u32;
@@ -318,6 +336,7 @@ fn punch_packet(
punch_reply.ipv6 = ipv6.octets().to_vec();
}
punch_reply.nat_type = protobuf::EnumOrUnknown::new(PunchNatType::from(nat_info.nat_type));
punch_reply.punch_model = protobuf::EnumOrUnknown::new(nat_info.punch_model.into());
log::info!("请求打洞={:?}", punch_reply);
let bytes = punch_reply
.write_to_bytes()
+9 -2
View File
@@ -29,9 +29,13 @@ fn retrieve_nat_type0(
.name("natTest".into())
.spawn(move || {
if nat_test.can_update() {
let local_ipv4 = nat::local_ipv4();
let local_ipv4 = if nat_test.update_local_ipv4 {
nat::local_ipv4()
} else {
None
};
let local_ipv6 = nat::local_ipv6();
match nat_test.re_test(local_ipv4, local_ipv6) {
match nat_test.re_test(local_ipv4, local_ipv6, context.default_interface()) {
Ok(nat_info) => {
log::info!("当前nat信息:{:?}", nat_info);
if let Err(e) = context.switch(nat_info.nat_type, &udp_socket_sender) {
@@ -42,6 +46,9 @@ fn retrieve_nat_type0(
log::warn!("nat re_test {:?}", e);
}
};
#[cfg(feature = "upnp")]
nat_test.reset_upnp();
log::info!("刷新nat结束")
}
})
.expect("natTest");
+7 -30
View File
@@ -3,7 +3,7 @@ use crate::handle::CurrentDeviceInfo;
use crate::proto::message::{ClientStatusInfo, PunchNatType, RouteItem};
use crate::protocol::body::ENCRYPTION_RESERVED;
use crate::protocol::{service_packet, NetPacket, Protocol, HEAD_LEN, MAX_TTL};
use crate::util::{Scheduler, WatchSingleU64Adder, WatchU64Adder};
use crate::util::Scheduler;
use crossbeam_utils::atomic::AtomicCell;
use protobuf::Message;
use std::io;
@@ -15,17 +15,9 @@ pub fn up_status(
scheduler: &Scheduler,
context: ChannelContext,
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
down_count_watcher: WatchU64Adder,
up_count_watcher: WatchSingleU64Adder,
) {
let _ = scheduler.timeout(Duration::from_secs(60), move |x| {
up_status0(
x,
context,
current_device_info,
down_count_watcher,
up_count_watcher,
)
up_status0(x, context, current_device_info)
});
}
@@ -33,25 +25,12 @@ fn up_status0(
scheduler: &Scheduler,
context: ChannelContext,
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
down_count_watcher: WatchU64Adder,
up_count_watcher: WatchSingleU64Adder,
) {
if let Err(e) = send_up_status_packet(
&context,
&current_device_info,
&down_count_watcher,
&up_count_watcher,
) {
if let Err(e) = send_up_status_packet(&context, &current_device_info) {
log::warn!("{:?}", e)
}
let rs = scheduler.timeout(Duration::from_secs(10 * 60), move |x| {
up_status0(
x,
context,
current_device_info,
down_count_watcher,
up_count_watcher,
)
up_status0(x, context, current_device_info)
});
if !rs {
log::info!("定时任务停止");
@@ -61,8 +40,6 @@ fn up_status0(
fn send_up_status_packet(
context: &ChannelContext,
current_device_info: &AtomicCell<CurrentDeviceInfo>,
down_count_watcher: &WatchU64Adder,
up_count_watcher: &WatchSingleU64Adder,
) -> io::Result<()> {
let device_info = current_device_info.load();
if device_info.status.offline() {
@@ -79,8 +56,8 @@ fn send_up_status_packet(
item.next_ip = ip.into();
message.p2p_list.push(item);
}
message.up_stream = up_count_watcher.get();
message.down_stream = down_count_watcher.get();
message.up_stream = context.up_traffic_meter.as_ref().map_or(0, |v| v.total());
message.down_stream = context.down_traffic_meter.as_ref().map_or(0, |v| v.total());
message.nat_type = protobuf::EnumOrUnknown::new(if context.is_cone() {
PunchNatType::Cone
} else {
@@ -99,6 +76,6 @@ fn send_up_status_packet(
net_packet.set_source(device_info.virtual_ip);
net_packet.set_destination(device_info.virtual_gateway);
net_packet.set_payload(&buf)?;
context.send_default(net_packet.buffer(), device_info.connect_server)?;
context.send_default(&net_packet, device_info.connect_server)?;
Ok(())
}
+32 -4
View File
@@ -1,5 +1,6 @@
use crate::channel::socket::LocalInterface;
use crossbeam_utils::atomic::AtomicCell;
use std::net::{Ipv4Addr, SocketAddr};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
pub mod callback;
mod extension;
@@ -29,6 +30,7 @@ pub struct PeerDeviceInfo {
pub status: PeerDeviceStatus,
pub client_secret: bool,
pub client_secret_hash: Vec<u8>,
pub wireguard: bool,
}
impl PeerDeviceInfo {
@@ -38,6 +40,7 @@ impl PeerDeviceInfo {
status: u8,
client_secret: bool,
client_secret_hash: Vec<u8>,
wireguard: bool,
) -> Self {
Self {
virtual_ip,
@@ -45,6 +48,7 @@ impl PeerDeviceInfo {
status: PeerDeviceStatus::from(status),
client_secret,
client_secret_hash,
wireguard,
}
}
}
@@ -66,6 +70,8 @@ pub struct BaseConfigInfo {
#[cfg(feature = "integrated_tun")]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
pub device_name: Option<String>,
pub allow_wire_guard: bool,
pub default_interface: LocalInterface,
}
impl BaseConfigInfo {
@@ -85,6 +91,8 @@ impl BaseConfigInfo {
#[cfg(feature = "integrated_tun")]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
device_name: Option<String>,
allow_wire_guard: bool,
default_interface: LocalInterface,
) -> Self {
Self {
name,
@@ -102,6 +110,8 @@ impl BaseConfigInfo {
#[cfg(feature = "integrated_tun")]
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
device_name,
allow_wire_guard,
default_interface,
}
}
}
@@ -116,6 +126,9 @@ impl PeerDeviceStatus {
pub fn is_online(&self) -> bool {
self == &PeerDeviceStatus::Online
}
pub fn is_offline(&self) -> bool {
self == &PeerDeviceStatus::Offline
}
}
impl Into<u8> for PeerDeviceStatus {
@@ -210,10 +223,10 @@ impl CurrentDeviceInfo {
virtual_gateway: Ipv4Addr,
) {
let broadcast_ip = (!u32::from_be_bytes(virtual_netmask.octets()))
| u32::from_be_bytes(virtual_gateway.octets());
| u32::from_be_bytes(virtual_ip.octets());
let broadcast_ip = Ipv4Addr::from(broadcast_ip);
let virtual_network = u32::from_be_bytes(virtual_netmask.octets())
& u32::from_be_bytes(virtual_gateway.octets());
let virtual_network =
u32::from_be_bytes(virtual_netmask.octets()) & u32::from_be_bytes(virtual_ip.octets());
let virtual_network = Ipv4Addr::from(virtual_network);
self.virtual_ip = virtual_ip;
self.virtual_netmask = virtual_netmask;
@@ -229,9 +242,24 @@ impl CurrentDeviceInfo {
pub fn virtual_gateway(&self) -> Ipv4Addr {
self.virtual_gateway
}
#[inline]
pub fn is_gateway(&self, ip: &Ipv4Addr) -> bool {
&self.virtual_gateway == ip || ip == &GATEWAY_IP
}
#[inline]
pub fn not_in_network(&self, ip: Ipv4Addr) -> bool {
u32::from(ip) & u32::from(self.virtual_netmask) != u32::from(self.virtual_network)
}
pub fn is_server_addr(&self, addr: SocketAddr) -> bool {
if self.connect_server == addr {
return true;
}
let f = |ip: IpAddr| match ip {
IpAddr::V4(v4) => Some(v4),
IpAddr::V6(v6) => v6.to_ipv4(),
};
addr.port() == self.connect_server.port() && f(addr.ip()) == f(self.connect_server.ip())
}
}
pub fn change_status(
current_device: &AtomicCell<CurrentDeviceInfo>,
+19 -10
View File
@@ -140,7 +140,7 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
net_packet.set_destination(source);
//不管加不加密,和接收到的数据长度都一致
self.client_cipher.encrypt_ipv4(&mut net_packet)?;
context.send_by_key(net_packet.buffer(), route_key)?;
context.send_by_key(&net_packet, route_key)?;
return Ok(());
}
}
@@ -194,6 +194,9 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
}
self.device.write(net_packet.payload())?;
}
ip_turn_packet::Protocol::WGIpv4 => {
// WG客户端的数据不会直接发过来,不用处理
}
ip_turn_packet::Protocol::Ipv4Broadcast => {
//客户端不帮忙转发广播包,所以不会出现这种类型的数据
}
@@ -212,14 +215,14 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
let source = net_packet.source();
match ControlPacket::new(net_packet.transport_protocol(), net_packet.payload())? {
ControlPacket::PingPacket(_) => {
let route = Route::from_default_rt(route_key, metric);
context.route_table.add_route_if_absent(source, route);
net_packet.set_transport_protocol(control_packet::Protocol::Pong.into());
net_packet.set_source(current_device.virtual_ip);
net_packet.set_destination(source);
net_packet.first_set_ttl(MAX_TTL);
self.client_cipher.encrypt_ipv4(&mut net_packet)?;
context.send_by_key(net_packet.buffer(), route_key)?;
let route = Route::from_default_rt(route_key, metric);
context.route_table.add_route_if_absent(source, route);
context.send_by_key(&net_packet, route_key)?;
}
ControlPacket::PongPacket(pong_packet) => {
let current_time = crate::handle::now_time() as u16;
@@ -238,7 +241,7 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
//忽略掉来源于自己的包
if self
.nat_test
.is_local_address(route_key.is_tcp(), route_key.addr)
.is_local_address(route_key.protocol().is_base_tcp(), route_key.addr)
{
return Ok(());
}
@@ -249,7 +252,7 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
net_packet.set_destination(source);
net_packet.first_set_ttl(1);
self.client_cipher.encrypt_ipv4(&mut net_packet)?;
context.send_by_key(net_packet.buffer(), route_key)?;
context.send_by_key(&net_packet, route_key)?;
// 收到PunchRequest就添加路由,会导致单向通信的问题,删掉试试
// let route = Route::from_default_rt(route_key, 1);
// context.route_table.add_route_if_absent(source, route);
@@ -261,11 +264,11 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
}
if self
.nat_test
.is_local_address(route_key.is_tcp(), route_key.addr)
.is_local_address(route_key.protocol().is_base_tcp(), route_key.addr)
{
return Ok(());
}
let route = Route::from_default_rt(route_key, 1);
let route = Route::from_default_rt(route_key, metric);
context.route_table.add_route_if_absent(source, route);
}
ControlPacket::AddrRequest => match route_key.addr.ip() {
@@ -281,7 +284,7 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
addr_packet.set_ipv4(ipv4);
addr_packet.set_port(route_key.addr.port());
self.client_cipher.encrypt_ipv4(&mut packet)?;
context.send_by_key(packet.buffer(), route_key)?;
context.send_by_key(&packet, route_key)?;
}
std::net::IpAddr::V6(_) => {}
},
@@ -311,6 +314,7 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
.collect();
let local_ipv4 = Some(Ipv4Addr::from(punch_info.local_ip.to_be_bytes()));
let tcp_port = punch_info.tcp_port as u16;
let public_tcp_port = punch_info.public_tcp_port as u16;
let ipv6 = if punch_info.ipv6.len() == 16 {
let ipv6: [u8; 16] = punch_info.ipv6.try_into().unwrap();
Some(Ipv6Addr::from(ipv6))
@@ -333,7 +337,9 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
ipv6,
punch_info.udp_ports.iter().map(|e| *e as u16).collect(),
tcp_port,
public_tcp_port,
punch_info.nat_type.enum_value_or_default().into(),
punch_info.punch_model.enum_value_or_default().into(),
);
{
let peer_nat_info = peer_nat_info.clone();
@@ -353,8 +359,11 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
nat_info.public_ports.iter().map(|e| *e as u32).collect();
punch_reply.public_port_range = nat_info.public_port_range as u32;
punch_reply.tcp_port = nat_info.tcp_port as u32;
punch_reply.public_tcp_port = nat_info.public_tcp_port as u32;
punch_reply.nat_type =
protobuf::EnumOrUnknown::new(PunchNatType::from(nat_info.nat_type));
punch_reply.punch_model =
protobuf::EnumOrUnknown::new(nat_info.punch_model.into());
punch_reply.local_ip =
u32::from(nat_info.local_ipv4().unwrap_or(Ipv4Addr::UNSPECIFIED));
punch_reply.local_port = nat_info.udp_ports[0] as u32;
@@ -377,7 +386,7 @@ impl<Device: DeviceWrite> ClientPacketHandler<Device> {
punch_packet.set_payload(&bytes)?;
self.client_cipher.encrypt_ipv4(&mut punch_packet)?;
if self.punch_sender.send(true, source, peer_nat_info) {
context.send_by_key(punch_packet.buffer(), route_key)?;
context.send_by_key(&punch_packet, route_key)?;
}
} else {
self.punch_sender.send(false, source, peer_nat_info);
+10 -11
View File
@@ -26,7 +26,6 @@ use crate::ip_proxy::IpProxyMap;
use crate::nat::NatTest;
use crate::protocol::{NetPacket, HEAD_LEN};
use crate::tun_tap_device::vnt_device::DeviceWrite;
use crate::util::U64Adder;
mod client;
mod server;
@@ -38,13 +37,12 @@ pub struct RecvDataHandler<Call, Device> {
turn: TurnPacketHandler,
client: ClientPacketHandler<Device>,
server: ServerPacketHandler<Call, Device>,
counter: U64Adder,
nat_test: NatTest,
}
impl<Call: VntCallback, Device: DeviceWrite> RecvChannelHandler for RecvDataHandler<Call, Device> {
fn handle(
&mut self,
&self,
buf: &mut [u8],
extend: &mut [u8],
route_key: RouteKey,
@@ -54,7 +52,7 @@ impl<Call: VntCallback, Device: DeviceWrite> RecvChannelHandler for RecvDataHand
return;
}
//判断stun响应包
if !route_key.is_tcp() {
if route_key.protocol().is_udp() {
if let Ok(rs) = self
.nat_test
.recv_data(route_key.index(), route_key.addr, buf)
@@ -82,7 +80,7 @@ impl<Call: VntCallback, Device: DeviceWrite> RecvDataHandler<Call, Device> {
client_cipher: Cipher,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
device: Device,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
config_info: BaseConfigInfo,
nat_test: NatTest,
callback: Call,
@@ -93,7 +91,6 @@ impl<Call: VntCallback, Device: DeviceWrite> RecvDataHandler<Call, Device> {
#[cfg(feature = "integrated_tun")]
#[cfg(feature = "ip_proxy")]
ip_proxy_map: Option<IpProxyMap>,
counter: U64Adder,
handshake: Handshake,
#[cfg(feature = "integrated_tun")]
tun_device_helper: crate::tun_tap_device::tun_create_helper::TunDeviceHelper,
@@ -104,7 +101,7 @@ impl<Call: VntCallback, Device: DeviceWrite> RecvDataHandler<Call, Device> {
server_cipher,
current_device.clone(),
device.clone(),
device_list,
device_map,
config_info,
nat_test.clone(),
callback,
@@ -130,20 +127,18 @@ impl<Call: VntCallback, Device: DeviceWrite> RecvDataHandler<Call, Device> {
turn,
client,
server,
counter,
nat_test,
}
}
fn handle0(
&mut self,
&self,
buf: &mut [u8],
extend: &mut [u8],
route_key: RouteKey,
context: &ChannelContext,
) -> anyhow::Result<()> {
// 统计流量
self.counter.add(buf.len() as _);
let net_packet = NetPacket::new(buf)?;
let extend = NetPacket::unchecked(extend);
if net_packet.ttl() == 0 || net_packet.source_ttl() < net_packet.ttl() {
log::warn!("丢弃过时包:{:?} {}", net_packet.head(), route_key.addr);
@@ -158,6 +153,10 @@ impl<Call: VntCallback, Device: DeviceWrite> RecvDataHandler<Call, Device> {
|| dest.is_unspecified()
|| dest == current_device.broadcast_ip
{
// 统计流量
if let Some(down_traffic_meter) = &context.down_traffic_meter {
down_traffic_meter.add_traffic(net_packet.source(), net_packet.data_len())
}
//发给自己的包
if net_packet.is_gateway() {
//服务端-客户端包
+61 -27
View File
@@ -1,4 +1,5 @@
use anyhow::anyhow;
use std::collections::HashMap;
use std::io;
use std::net::Ipv4Addr;
use std::sync::Arc;
@@ -24,9 +25,7 @@ use crate::handle::callback::{ErrorInfo, ErrorType, HandshakeInfo, RegisterInfo,
use crate::handle::handshaker;
use crate::handle::handshaker::Handshake;
use crate::handle::recv_data::PacketHandler;
use crate::handle::{
registrar, BaseConfigInfo, ConnectStatus, CurrentDeviceInfo, PeerDeviceInfo, GATEWAY_IP,
};
use crate::handle::{registrar, BaseConfigInfo, ConnectStatus, CurrentDeviceInfo, PeerDeviceInfo};
use crate::nat::NatTest;
use crate::proto::message::{DeviceList, HandshakeResponse, RegistrationResponse};
use crate::protocol::body::ENCRYPTION_RESERVED;
@@ -44,7 +43,7 @@ pub struct ServerPacketHandler<Call, Device> {
server_cipher: Cipher,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
device: Device,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
config_info: BaseConfigInfo,
nat_test: NatTest,
callback: Call,
@@ -62,7 +61,7 @@ impl<Call, Device> ServerPacketHandler<Call, Device> {
server_cipher: Cipher,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
device: Device,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
config_info: BaseConfigInfo,
nat_test: NatTest,
callback: Call,
@@ -77,12 +76,16 @@ impl<Call, Device> ServerPacketHandler<Call, Device> {
server_cipher,
current_device,
device,
device_list,
device_map,
config_info,
nat_test,
callback,
#[cfg(feature = "server_encrypt")]
up_key_time: Arc::new(AtomicCell::new(Instant::now() - Duration::from_secs(60))),
up_key_time: Arc::new(AtomicCell::new(
Instant::now()
.checked_sub(Duration::from_secs(60))
.unwrap_or(Instant::now()),
)),
external_route,
handshake,
#[cfg(feature = "integrated_tun")]
@@ -100,6 +103,14 @@ impl<Call: VntCallback, Device: DeviceWrite> PacketHandler for ServerPacketHandl
context: &ChannelContext,
current_device: &CurrentDeviceInfo,
) -> anyhow::Result<()> {
if !current_device.is_server_addr(route_key.addr) {
//拦截不是服务端的流量
log::warn!(
"route_key={:?},不是来源于服务端地址{}",
route_key,
current_device.connect_server
);
}
context
.route_table
.update_read_time(&net_packet.source(), &route_key);
@@ -129,7 +140,7 @@ impl<Call: VntCallback, Device: DeviceWrite> PacketHandler for ServerPacketHandl
self.config_info.token.clone(),
key,
)?;
context.send_by_key(packet.buffer(), route_key)?;
context.send_by_key(&packet, route_key)?;
}
}
}
@@ -140,6 +151,8 @@ impl<Call: VntCallback, Device: DeviceWrite> PacketHandler for ServerPacketHandl
let response = HandshakeResponse::parse_from_bytes(net_packet.payload())
.map_err(|e| anyhow!("HandshakeResponse {:?}", e))?;
log::info!("握手响应:{:?},{}", route_key, response);
//设置为默认通道
context.set_default_route_key(route_key);
//如果开启了加密,则发送加密握手请求
#[cfg(feature = "server_encrypt")]
if let Some(key) = self.server_cipher.key() {
@@ -153,7 +166,7 @@ impl<Call: VntCallback, Device: DeviceWrite> PacketHandler for ServerPacketHandl
key,
)?;
drop(guard);
context.send_by_key(packet.buffer(), route_key)?;
context.send_by_key(&packet, route_key)?;
return Ok(());
}
log::warn!(
@@ -188,7 +201,7 @@ impl<Call: VntCallback, Device: DeviceWrite> PacketHandler for ServerPacketHandl
self.config_info.token.clone(),
key,
)?;
context.send_by_key(packet.buffer(), route_key)?;
context.send_by_key(&packet, route_key)?;
self.rsa_cipher.lock().replace(rsa_cipher);
}
return Ok(());
@@ -200,7 +213,7 @@ impl<Call: VntCallback, Device: DeviceWrite> PacketHandler for ServerPacketHandl
let handshake_info = HandshakeInfo::new_no_secret(response.version);
if self.callback.handshake(handshake_info) {
//没有加密,则发送注册请求
self.register(current_device, context)?;
self.register(current_device, context, route_key)?;
}
return Ok(());
@@ -235,6 +248,11 @@ impl<Call: VntCallback, Device: DeviceWrite> PacketHandler for ServerPacketHandl
_ => {}
}
}
ip_turn_packet::Protocol::WGIpv4 => {
if self.config_info.allow_wire_guard {
self.device.write(net_packet.payload())?;
}
}
ip_turn_packet::Protocol::Ipv4Broadcast => {}
ip_turn_packet::Protocol::Unknown(_) => {}
}
@@ -279,6 +297,10 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
let public_port = response.public_port as u16;
self.nat_test
.update_addr(route_key.index(), public_ip, public_port);
if route_key.protocol().is_tcp() {
log::info!("更新公网tcp端口 {public_port}");
self.nat_test.update_tcp_port(public_port);
}
let old = current_device;
let mut cur = *current_device;
loop {
@@ -333,7 +355,10 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
target_os = "linux",
target_os = "macos"
))]
match crate::tun_tap_device::create_device(device_config) {
match crate::tun_tap_device::create_device(
device_config,
&self.callback,
) {
Ok(device) => {
use tun::device::IFace;
let tun_info = crate::handle::callback::DeviceInfo::new(
@@ -342,7 +367,8 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
);
log::info!("tun信息{:?}", tun_info);
self.callback.create_tun(tun_info);
self.tun_device_helper.start(device)?;
self.tun_device_helper
.start(device, self.config_info.allow_wire_guard)?;
}
Err(e) => {
log::error!("{:?}", e);
@@ -362,24 +388,25 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
let device_fd = self.callback.generate_tun(device_config);
if device_fd == 0 {
self.callback.error(ErrorInfo::new_msg(
ErrorType::Unknown,
ErrorType::FailedToCrateDevice,
"device_fd == 0".into(),
));
} else {
match tun::Device::new(device_fd as _) {
Ok(device) => {
if let Err(e) =
self.tun_device_helper.start(Arc::new(device))
{
if let Err(e) = self.tun_device_helper.start(
Arc::new(device),
self.config_info.allow_wire_guard,
) {
self.callback.error(ErrorInfo::new_msg(
ErrorType::Unknown,
ErrorType::FailedToCrateDevice,
format!("{:?}", e),
));
}
}
Err(e) => {
self.callback.error(ErrorInfo::new_msg(
ErrorType::Unknown,
ErrorType::FailedToCrateDevice,
format!("{:?}", e),
));
}
@@ -403,7 +430,7 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
service_packet::Protocol::SecretHandshakeResponse => {
log::info!("SecretHandshakeResponse");
//加密握手结束,发送注册数据
self.register(current_device, context)?;
self.register(current_device, context, route_key)?;
}
_ => {
log::warn!(
@@ -424,14 +451,18 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
info.device_status as u8,
info.client_secret,
info.client_secret_hash,
info.wireguard,
)
})
.collect();
{
let mut dev = self.device_list.lock();
let mut dev = self.device_map.lock();
//这里可能会收到旧的消息,但是随着时间推移总会收到新的
dev.0 = epoch;
dev.1 = ip_list.clone();
dev.1.clear();
for info in ip_list.clone() {
dev.1.insert(info.virtual_ip, info);
}
}
self.callback.peer_client_list(
ip_list
@@ -444,11 +475,14 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
&self,
current_device: &CurrentDeviceInfo,
context: &ChannelContext,
route_key: RouteKey,
) -> anyhow::Result<()> {
if current_device.status.online() {
log::info!("已连接的不需要注册,{:?}", self.config_info);
return Ok(());
}
//设置为默认通道
context.set_default_route_key(route_key);
let token = self.config_info.token.clone();
let device_id = self.config_info.device_id.clone();
let name = self.config_info.name.clone();
@@ -473,7 +507,7 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
)?;
log::info!("发送注册请求,{:?}", self.config_info);
//注册请求只发送到默认通道
context.send_default(response.buffer(), current_device.connect_server)?;
context.send_default(&response, current_device.connect_server)?;
Ok(())
}
fn error(
@@ -495,7 +529,7 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
self.callback.error(err);
//掉线epoch要归零
{
let mut dev = self.device_list.lock();
let mut dev = self.device_map.lock();
dev.0 = 0;
drop(dev);
}
@@ -543,12 +577,12 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
let rt = (current_time - pong_packet.time()) as i64;
let route = Route::from(route_key, metric, rt);
context.route_table.add_route(net_packet.source(), route);
let epoch = self.device_list.lock().0;
let epoch = self.device_map.lock().0;
if pong_packet.epoch() != epoch {
//纪元不一致,可能有新客户端连接,向服务端拉取客户端列表
let mut poll_device = NetPacket::new_encrypt([0; 12 + ENCRYPTION_RESERVED])?;
poll_device.set_source(current_device.virtual_ip);
poll_device.set_destination(GATEWAY_IP);
poll_device.set_destination(current_device.virtual_gateway);
poll_device.set_default_version();
poll_device.set_gateway_flag(true);
poll_device.first_set_ttl(MAX_TTL);
@@ -557,7 +591,7 @@ impl<Call: VntCallback, Device: DeviceWrite> ServerPacketHandler<Call, Device> {
.set_transport_protocol(service_packet::Protocol::PullDeviceList.into());
self.server_cipher.encrypt_ipv4(&mut poll_device)?;
//发送到默认服务端即可
context.send_default(poll_device.buffer(), current_device.connect_server)?;
context.send_default(&poll_device, current_device.connect_server)?;
}
}
ControlPacket::AddrResponse(addr_packet) => {
+5 -1
View File
@@ -27,6 +27,10 @@ impl PacketHandler for TurnPacketHandler {
// ttl减一
let ttl = net_packet.incr_ttl();
if ttl > 0 {
if net_packet.is_gateway() {
// 暂时不转发服务端包
return Ok(());
}
let destination = net_packet.destination();
if let Some(route) = context.route_table.route_one(&destination) {
if route.addr == route_key.addr {
@@ -36,7 +40,7 @@ impl PacketHandler for TurnPacketHandler {
}
if route.metric <= ttl {
return context
.send_by_key(net_packet.buffer(), route.route_key())
.send_by_key(&net_packet, route.route_key())
.context("转发失败");
}
}
+4 -6
View File
@@ -18,28 +18,26 @@ pub(crate) use windows::*;
/// 仅仅是停止tun,不停止vnt
#[derive(Clone, Default)]
pub struct DeviceStop {
f: Arc<Mutex<Option<Box<dyn FnOnce() -> bool + Send>>>>,
f: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>,
stopped: Arc<AtomicCell<bool>>,
}
impl DeviceStop {
pub fn set_stop_fn<F>(&self, f: F)
where
F: FnOnce() -> bool + Send + 'static,
F: FnOnce() + Send + 'static,
{
self.f.lock().replace(Box::new(f));
}
pub fn stop(&self) -> bool {
pub fn stop(&self) {
if let Some(f) = self.f.lock().take() {
f()
} else {
false
}
}
pub fn stopped(&self) {
self.stopped.store(true);
}
pub fn is_stop(&self) -> bool {
pub fn is_stopped(&self) -> bool {
self.stopped.load()
}
}
+61 -58
View File
@@ -1,10 +1,10 @@
use crossbeam_utils::atomic::AtomicCell;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::Arc;
use std::{io, thread};
use crossbeam_utils::atomic::AtomicCell;
use parking_lot::Mutex;
use packet::icmp::icmp::IcmpPacket;
use packet::icmp::Kind;
use packet::ip::ipv4::packet::IpV4Packet;
@@ -13,6 +13,7 @@ use tun::device::IFace;
use tun::Device;
use crate::channel::context::ChannelContext;
use crate::channel::sender::{send_to_wg, send_to_wg_broadcast};
use crate::cipher::Cipher;
use crate::compression::Compressor;
use crate::external_route::ExternalRoute;
@@ -26,13 +27,7 @@ use crate::protocol;
use crate::protocol::body::ENCRYPTION_RESERVED;
use crate::protocol::ip_turn_packet::BroadcastPacket;
use crate::protocol::{ip_turn_packet, NetPacket, MAX_TTL};
use crate::util::{SingleU64Adder, StopManager};
/// 是否在一个网段
#[inline]
fn check_dest(dest: Ipv4Addr, virtual_netmask: Ipv4Addr, virtual_network: Ipv4Addr) -> bool {
u32::from_be_bytes(dest.octets()) & u32::from_be_bytes(virtual_netmask.octets())
== u32::from_be_bytes(virtual_network.octets())
}
use crate::util::StopManager;
fn icmp(device_writer: &Device, mut ipv4_packet: IpV4Packet<&mut [u8]>) -> anyhow::Result<()> {
if ipv4_packet.protocol() == Protocol::Icmp {
let mut icmp = IcmpPacket::new(ipv4_packet.payload_mut())?;
@@ -58,10 +53,10 @@ pub fn start(
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
mut up_counter: SingleU64Adder,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
compressor: Compressor,
device_stop: DeviceStop,
allow_wire_guard: bool,
) -> io::Result<()> {
thread::Builder::new()
.name("tunHandlerS".into())
@@ -76,10 +71,10 @@ pub fn start(
ip_proxy_map,
client_cipher,
server_cipher,
&mut up_counter,
device_list,
device_map,
compressor,
device_stop,
allow_wire_guard,
) {
log::warn!("stop:{}", e);
}
@@ -93,18 +88,21 @@ fn broadcast(
sender: &ChannelContext,
net_packet: &mut NetPacket<&mut [u8]>,
current_device: &CurrentDeviceInfo,
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
device_map: &Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>,
) -> anyhow::Result<()> {
let list: Vec<Ipv4Addr> = device_list
let list: Vec<Ipv4Addr> = device_map
.lock()
.1
.iter()
.filter(|info| info.status.is_online())
.values()
.filter(|info| !info.wireguard && info.status.is_online())
.map(|info| info.virtual_ip)
.collect();
if list.is_empty() {
return Ok(());
}
const MAX_COUNT: usize = 8;
let mut p2p_ips = Vec::with_capacity(8);
let mut relay_ips = Vec::with_capacity(8);
let mut relay = false;
let mut overflow = false;
for (index, peer_ip) in list.into_iter().enumerate() {
if index > MAX_COUNT {
@@ -112,46 +110,27 @@ fn broadcast(
break;
}
if let Some(route) = sender.route_table.route_one_p2p(&peer_ip) {
if sender
.send_by_key(net_packet.buffer(), route.route_key())
.is_ok()
{
if sender.send_by_key(&net_packet, route.route_key()).is_ok() {
p2p_ips.push(peer_ip);
continue;
}
}
relay_ips.push(peer_ip);
relay = true;
}
if !overflow && relay_ips.is_empty() {
if !overflow && !relay {
//全部p2p,不需要服务器中转
return Ok(());
}
if p2p_ips.is_empty() {
//都没有p2p则直接由服务器转发
if current_device.status.online() {
sender.send_default(net_packet.buffer(), current_device.connect_server)?;
}
return Ok(());
}
if !overflow && relay_ips.len() == 2 {
// 如果转发的ip数不多就直接发
for peer_ip in relay_ips {
//非直连的广播要改变目的地址,不然服务端收到了会再次广播
net_packet.set_destination(peer_ip);
sender.send_ipv4_by_id(
net_packet.buffer(),
&peer_ip,
current_device.connect_server,
current_device.status.online(),
)?;
}
return Ok(());
}
if current_device.status.offline() {
//离线的不再转发
return Ok(());
}
if p2p_ips.is_empty() {
//都没有p2p则直接由服务器转发
sender.send_default(&net_packet, current_device.connect_server)?;
return Ok(());
}
let buf = vec![0u8; 12 + 1 + p2p_ips.len() * 4 + net_packet.data_len() + ENCRYPTION_RESERVED];
//剩余的发送到服务端,需要告知哪些已发送过
let mut server_packet = NetPacket::new_encrypt(buf)?;
@@ -168,7 +147,7 @@ fn broadcast(
broadcast.set_address(&p2p_ips)?;
broadcast.set_data(net_packet.buffer())?;
server_cipher.encrypt_ipv4(&mut server_packet)?;
sender.send_default(server_packet.buffer(), current_device.connect_server)?;
sender.send_default(&server_packet, current_device.connect_server)?;
Ok(())
}
@@ -187,8 +166,9 @@ pub(crate) fn handle(
#[cfg(feature = "ip_proxy")] proxy_map: &Option<IpProxyMap>,
client_cipher: &Cipher,
server_cipher: &Cipher,
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
device_map: &Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>,
compressor: &Compressor,
allow_wire_guard: bool,
) -> anyhow::Result<()> {
//忽略掉结构不对的情况(ipv6数据、win tap会读到空数据),不然日志打印太多了
let ipv4_packet = match IpV4Packet::new(&mut buf[12..data_len]) {
@@ -216,17 +196,13 @@ pub(crate) fn handle(
if protocol == Protocol::Icmp {
net_packet.set_gateway_flag(true);
server_cipher.encrypt_ipv4(&mut net_packet)?;
context.send_default(net_packet.buffer(), current_device.connect_server)?;
context.send_default(&net_packet, current_device.connect_server)?;
}
return Ok(());
}
if !dest_ip.is_multicast() && !dest_ip.is_broadcast() && current_device.broadcast_ip != dest_ip
{
if !check_dest(
dest_ip,
current_device.virtual_netmask,
current_device.virtual_network,
) {
if current_device.not_in_network(dest_ip) {
if let Some(r_dest_ip) = ip_route.route(&dest_ip) {
//路由的目标不能是自己
if r_dest_ip == src_ip {
@@ -251,6 +227,33 @@ pub(crate) fn handle(
dest_ip = Ipv4Addr::BROADCAST;
net_packet.set_destination(Ipv4Addr::BROADCAST);
}
let is_broadcast = dest_ip.is_broadcast() || current_device.broadcast_ip == dest_ip;
if allow_wire_guard {
if is_broadcast {
// wg客户端和vnt客户端分开广播
let exists_wg = device_map
.lock()
.1
.values()
.any(|v| v.status.is_online() && v.wireguard);
if exists_wg {
send_to_wg_broadcast(context, &net_packet, server_cipher, &current_device)?;
}
} else {
// 如果是wg客户端则发到vnts转发
let guard = device_map.lock();
if let Some(peer_info) = guard.1.get(&dest_ip) {
if peer_info.status.is_offline() {
return Ok(());
}
if peer_info.wireguard {
drop(guard);
send_to_wg(context, &mut net_packet, server_cipher, &current_device)?;
return Ok(());
}
}
}
}
let mut net_packet = if compressor.compress(&net_packet, &mut out)? {
out.set_default_version();
@@ -263,7 +266,7 @@ pub(crate) fn handle(
} else {
net_packet
};
if dest_ip.is_broadcast() || current_device.broadcast_ip == dest_ip {
if is_broadcast {
// 广播 发送到直连目标
client_cipher.encrypt_ipv4(&mut net_packet)?;
broadcast(
@@ -271,14 +274,14 @@ pub(crate) fn handle(
context,
&mut net_packet,
&current_device,
device_list,
device_map,
)?;
return Ok(());
}
client_cipher.encrypt_ipv4(&mut net_packet)?;
context.send_ipv4_by_id(
net_packet.buffer(),
&net_packet,
&dest_ip,
current_device.connect_server,
current_device.status.online(),
+26 -33
View File
@@ -7,13 +7,15 @@ use crate::handle::tun_tap::DeviceStop;
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
#[cfg(feature = "ip_proxy")]
use crate::ip_proxy::IpProxyMap;
use crate::util::{SingleU64Adder, StopManager};
use crate::util::StopManager;
use crossbeam_utils::atomic::AtomicCell;
use mio::event::Source;
use mio::unix::SourceFd;
use mio::{Events, Interest, Poll, Token, Waker};
use parking_lot::Mutex;
use std::collections::HashMap;
use std::io;
use std::net::Ipv4Addr;
use std::os::fd::AsRawFd;
use std::sync::Arc;
use tun::Device;
@@ -30,41 +32,28 @@ pub(crate) fn start_simple(
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
up_counter: &mut SingleU64Adder,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
compressor: Compressor,
device_stop: DeviceStop,
allow_wire_guard: bool,
) -> anyhow::Result<()> {
let stop_all = Arc::new(AtomicCell::new(true));
let poll = Poll::new()?;
let waker = Arc::new(Waker::new(poll.registry(), STOP)?);
let _waker = waker.clone();
let device_cell = Arc::new(AtomicCell::new(Some(waker)));
let worker = {
let device_cell = device_cell.clone();
stop_manager.add_listener("tun_device".into(), move || {
if let Some(waker) = device_cell.take() {
if let Err(e) = waker.wake() {
log::warn!("{:?}", e);
}
if let Err(e) = waker.wake() {
log::warn!("{:?}", e);
}
})?
};
{
let stop_all = stop_all.clone();
device_stop.set_stop_fn(move || {
if let Some(waker) = device_cell.take() {
stop_all.store(false);
if let Err(e) = waker.wake() {
log::warn!("{:?}", e);
return false;
}
true
} else {
false
}
});
}
let worker_cell = Arc::new(AtomicCell::new(Some(worker)));
let _worker_cell = worker_cell.clone();
device_stop.set_stop_fn(move || {
if let Some(worker) = _worker_cell.take() {
worker.stop_self()
}
});
if let Err(e) = start_simple0(
poll,
context,
@@ -75,14 +64,14 @@ pub(crate) fn start_simple(
ip_proxy_map,
client_cipher,
server_cipher,
up_counter,
device_list,
device_map,
compressor,
allow_wire_guard,
) {
log::error!("{:?}", e);
};
device_stop.stopped();
if stop_all.load() {
if let Some(worker) = worker_cell.take() {
worker.stop_all();
}
drop(_waker);
@@ -98,9 +87,9 @@ fn start_simple0(
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
up_counter: &mut SingleU64Adder,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
compressor: Compressor,
allow_wire_guard: bool,
) -> anyhow::Result<()> {
let mut buf = [0; BUFFER_SIZE];
let mut extend = [0; BUFFER_SIZE];
@@ -121,18 +110,21 @@ fn start_simple0(
if event.token() == STOP {
return Ok(());
}
let mut retries = 0;
loop {
let len = match fd.read(&mut buf[start..]) {
Ok(len) => len + start,
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
retries += 1;
if retries < 8 {
continue;
}
break;
}
Err(e)?
}
};
//单线程的
up_counter.add(len as u64);
// buf是重复利用的,需要重置头部
buf[..12].fill(0);
match crate::handle::tun_tap::tun_handler::handle(
@@ -147,8 +139,9 @@ fn start_simple0(
&ip_proxy_map,
&client_cipher,
&server_cipher,
&device_list,
&device_map,
&compressor,
allow_wire_guard,
) {
Ok(_) => {}
Err(e) => {
+20 -27
View File
@@ -7,9 +7,11 @@ use crate::handle::tun_tap::DeviceStop;
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
#[cfg(feature = "ip_proxy")]
use crate::ip_proxy::IpProxyMap;
use crate::util::{SingleU64Adder, StopManager};
use crate::util::StopManager;
use crossbeam_utils::atomic::AtomicCell;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::Arc;
use tun::device::IFace;
use tun::Device;
@@ -23,35 +25,26 @@ pub(crate) fn start_simple(
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
up_counter: &mut SingleU64Adder,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
compressor: Compressor,
device_stop: DeviceStop,
allow_wire_guard: bool,
) -> anyhow::Result<()> {
let device_cell = Arc::new(AtomicCell::new(Some(device.clone())));
let stop_all = Arc::new(AtomicCell::new(true));
let worker = {
let device_cell = device_cell.clone();
let device = device.clone();
stop_manager.add_listener("tun_device".into(), move || {
if let Some(device) = device_cell.take() {
if let Err(e) = device.shutdown() {
log::warn!("{:?}", e);
}
if let Err(e) = device.shutdown() {
log::warn!("{:?}", e);
}
})?
};
let worker_cell = Arc::new(AtomicCell::new(Some(worker)));
{
let stop_all = stop_all.clone();
let worker_cell = worker_cell.clone();
device_stop.set_stop_fn(move || {
if let Some(device) = device_cell.take() {
stop_all.store(false);
if let Err(e) = device.shutdown() {
log::warn!("{:?}", e);
return false;
}
true
} else {
false
if let Some(worker) = worker_cell.take() {
worker.stop_self()
}
});
}
@@ -64,14 +57,14 @@ pub(crate) fn start_simple(
ip_proxy_map,
client_cipher,
server_cipher,
up_counter,
device_list,
device_map,
compressor,
allow_wire_guard,
) {
log::error!("{:?}", e);
}
device_stop.stopped();
if stop_all.load() {
if let Some(worker) = worker_cell.take() {
worker.stop_all();
}
Ok(())
@@ -85,16 +78,15 @@ fn start_simple0(
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
up_counter: &mut SingleU64Adder,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
compressor: Compressor,
allow_wire_guard: bool,
) -> anyhow::Result<()> {
let mut buf = [0; BUFFER_SIZE];
let mut extend = [0; BUFFER_SIZE];
loop {
let len = device.read(&mut buf[12..])? + 12;
//单线程的
up_counter.add(len as u64);
// buf是重复利用的,需要重置头部
buf[..12].fill(0);
match crate::handle::tun_tap::tun_handler::handle(
@@ -109,8 +101,9 @@ fn start_simple0(
&ip_proxy_map,
&client_cipher,
&server_cipher,
&device_list,
&device_map,
&compressor,
allow_wire_guard,
) {
Ok(_) => {}
Err(e) => {
+6 -1
View File
@@ -13,6 +13,7 @@ use packet::icmp::icmp::HeaderOther;
use packet::ip::ipv4::packet::IpV4Packet;
use crate::channel::context::ChannelContext;
use crate::channel::socket::{LocalInterface, VntSocketTrait};
use crate::cipher::Cipher;
use crate::handle::CurrentDeviceInfo;
use crate::ip_proxy::ProxyHandler;
@@ -30,6 +31,7 @@ impl IcmpProxy {
context: ChannelContext,
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
client_cipher: Cipher,
default_interface: &LocalInterface,
) -> anyhow::Result<Self> {
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
let icmp_socket = socket2::Socket::new(
@@ -50,6 +52,9 @@ impl IcmpProxy {
.bind(&socket2::SockAddr::from(addr))
.context("bind Socket ICMPV4 failed")?;
icmp_socket.set_nonblocking(true)?;
if let Err(e) = icmp_socket.set_ip_unicast_if(default_interface) {
log::warn!("set_ip_unicast_if {:?}", e)
}
let std_socket: std::net::UdpSocket = icmp_socket.into();
let tokio_icmp_socket = UdpSocket::from_std(std_socket.try_clone()?)?;
@@ -155,7 +160,7 @@ fn recv_handle(
return;
}
if let Err(e) = context.send_ipv4_by_id(
net_packet.buffer(),
&net_packet,
&dest_ip,
current_device.connect_server,
current_device.status.online(),
+6 -4
View File
@@ -68,14 +68,16 @@ pub fn init_proxy(
}
async fn init_proxy0(
_context: ChannelContext,
context: ChannelContext,
_current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
_client_cipher: Cipher,
) -> anyhow::Result<IpProxyMap> {
let default_interface = context.default_interface().clone();
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
let icmp_proxy = IcmpProxy::new(_context, _current_device, _client_cipher).await?;
let tcp_proxy = TcpProxy::new().await?;
let udp_proxy = UdpProxy::new().await?;
let icmp_proxy =
IcmpProxy::new(context, _current_device, _client_cipher, &default_interface).await?;
let tcp_proxy = TcpProxy::new(default_interface.clone()).await?;
let udp_proxy = UdpProxy::new(default_interface.clone()).await?;
Ok(IpProxyMap {
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
+32 -21
View File
@@ -5,13 +5,13 @@ use std::time::Duration;
use std::{collections::HashMap, io, net::SocketAddr};
use parking_lot::Mutex;
use tokio::net::{TcpListener, TcpSocket, TcpStream};
use tokio::net::{TcpListener, TcpStream};
use crate::channel::socket::{create_tcp, LocalInterface};
use crate::ip_proxy::ProxyHandler;
use packet::ip::ipv4::packet::IpV4Packet;
use packet::tcp::tcp::TcpPacket;
use crate::ip_proxy::ProxyHandler;
#[derive(Clone)]
pub struct TcpProxy {
port: u16,
@@ -19,7 +19,7 @@ pub struct TcpProxy {
}
impl TcpProxy {
pub async fn new() -> anyhow::Result<Self> {
pub async fn new(default_interface: LocalInterface) -> anyhow::Result<Self> {
let nat_map: Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>> =
Arc::new(Mutex::new(HashMap::with_capacity(16)));
let tcp_listener = TcpListener::bind(format!("0.0.0.0:{}", 0))
@@ -28,7 +28,7 @@ impl TcpProxy {
let port = tcp_listener.local_addr()?.port();
{
let nat_map = nat_map.clone();
tokio::spawn(tcp_proxy(tcp_listener, nat_map));
tokio::spawn(tcp_proxy(tcp_listener, nat_map, default_interface));
}
Ok(Self { port, nat_map })
}
@@ -79,26 +79,33 @@ impl ProxyHandler for TcpProxy {
async fn tcp_proxy(
tcp_listener: TcpListener,
nat_map: Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>>,
default_interface: LocalInterface,
) {
loop {
match tcp_listener.accept().await {
Ok((tcp_stream, sender_addr)) => match sender_addr {
SocketAddr::V4(sender_addr) => {
if let Some(dest_addr) = nat_map.lock().get(&sender_addr).cloned() {
let default_interface = default_interface.clone();
tokio::spawn(async move {
let peer_tcp_stream =
match tcp_connect(sender_addr.port(), dest_addr.into()).await {
Ok(peer_tcp_stream) => peer_tcp_stream,
Err(e) => {
log::warn!(
"tcp代理异常:{:?},来源:{},目标:{}",
e,
sender_addr,
dest_addr
);
return;
}
};
let peer_tcp_stream = match tcp_connect(
sender_addr.port(),
dest_addr.into(),
&default_interface,
)
.await
{
Ok(peer_tcp_stream) => peer_tcp_stream,
Err(e) => {
log::warn!(
"tcp代理异常:{:?},来源:{},目标:{}",
e,
sender_addr,
dest_addr
);
return;
}
};
proxy(sender_addr, dest_addr, tcp_stream, peer_tcp_stream).await
});
} else {
@@ -114,15 +121,19 @@ async fn tcp_proxy(
}
}
/// 优先使用来源端口建立tcp连接
async fn tcp_connect(src_port: u16, addr: SocketAddr) -> anyhow::Result<TcpStream> {
let socket = TcpSocket::new_v4()?;
async fn tcp_connect(
src_port: u16,
addr: SocketAddr,
default_interface: &LocalInterface,
) -> anyhow::Result<TcpStream> {
let socket = create_tcp(true, default_interface)?;
if socket
.bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, src_port).into())
.is_err()
{
socket.bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into())?;
}
let _ = socket.set_nodelay(false);
let _ = socket.set_nodelay(true);
let tcp_stream = tokio::time::timeout(Duration::from_secs(5), socket.connect(addr))
.await
.with_context(|| format!("TCP connection timeout {}", addr))?
+26 -15
View File
@@ -8,11 +8,11 @@ use std::{collections::HashMap, io, net::SocketAddr};
use parking_lot::Mutex;
use tokio::net::UdpSocket;
use crate::channel::socket::{bind_udp, LocalInterface};
use crate::ip_proxy::ProxyHandler;
use packet::ip::ipv4::packet::IpV4Packet;
use packet::udp::udp::UdpPacket;
use crate::ip_proxy::ProxyHandler;
#[derive(Clone)]
pub struct UdpProxy {
port: u16,
@@ -20,7 +20,7 @@ pub struct UdpProxy {
}
impl UdpProxy {
pub async fn new() -> anyhow::Result<Self> {
pub async fn new(default_interface: LocalInterface) -> anyhow::Result<Self> {
let nat_map: Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>> =
Arc::new(Mutex::new(HashMap::with_capacity(16)));
let udp = UdpSocket::bind(format!("0.0.0.0:{}", 0))
@@ -29,8 +29,8 @@ impl UdpProxy {
let port = udp.local_addr()?.port();
{
let nat_map = nat_map.clone();
tokio::spawn(async {
if let Err(e) = udp_proxy(udp, nat_map).await {
tokio::spawn(async move {
if let Err(e) = udp_proxy(udp, nat_map, default_interface).await {
log::warn!("udp_proxy:{:?}", e);
}
});
@@ -84,7 +84,8 @@ impl ProxyHandler for UdpProxy {
async fn udp_proxy(
udp: UdpSocket,
nat_map: Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>>,
) -> io::Result<()> {
default_interface: LocalInterface,
) -> anyhow::Result<()> {
let mut buf = [0u8; 65536];
let inner_map: Arc<Mutex<HashMap<SocketAddrV4, (Arc<UdpSocket>, Arc<AtomicCell<Instant>>)>>> =
@@ -94,9 +95,15 @@ async fn udp_proxy(
match udp_socket.recv_from(&mut buf).await {
Ok((len, sender_addr)) => match sender_addr {
SocketAddr::V4(sender_addr) => {
if let Err(e) =
udp_proxy0(&buf[..len], sender_addr, &inner_map, &nat_map, &udp_socket)
.await
if let Err(e) = udp_proxy0(
&buf[..len],
sender_addr,
&inner_map,
&nat_map,
&udp_socket,
&default_interface,
)
.await
{
log::warn!("udp proxy {} {:?}", sender_addr, e);
}
@@ -116,7 +123,8 @@ async fn udp_proxy0(
inner_map: &Arc<Mutex<HashMap<SocketAddrV4, (Arc<UdpSocket>, Arc<AtomicCell<Instant>>)>>>,
map: &Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>>,
udp_socket: &Arc<UdpSocket>,
) -> io::Result<()> {
default_interface: &LocalInterface,
) -> anyhow::Result<()> {
let option = inner_map.lock().get(&sender_addr).cloned();
if let Some((udp, time)) = option {
time.store(Instant::now());
@@ -125,11 +133,14 @@ async fn udp_proxy0(
let option = map.lock().get(&sender_addr).cloned();
if let Some(dest_addr) = option {
//先使用相同的端口,冲突了再随机端口
let peer_udp_socket =
match UdpSocket::bind(format!("0.0.0.0:{}", sender_addr.port())).await {
Ok(udp) => udp,
Err(_) => UdpSocket::bind("0.0.0.0:0").await?,
};
let peer_udp_socket = match bind_udp(
format!("0.0.0.0:{}", sender_addr.port()).parse().unwrap(),
default_interface,
) {
Ok(udp) => udp,
Err(_) => bind_udp("0.0.0.0:0".parse().unwrap(), default_interface)?,
};
let peer_udp_socket = UdpSocket::from_std(peer_udp_socket.into())?;
peer_udp_socket.connect(dest_addr).await?;
peer_udp_socket.send(buf).await?;
let peer_udp_socket = Arc::new(peer_udp_socket);
+114 -42
View File
@@ -1,17 +1,19 @@
use anyhow::Context;
use anyhow::{anyhow, Context};
use std::io;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
use std::net::{SocketAddr, UdpSocket};
use std::ops::Sub;
use std::sync::Arc;
use std::time::{Duration, Instant};
use crossbeam_utils::atomic::AtomicCell;
use parking_lot::Mutex;
use rand::prelude::SliceRandom;
use rand::Rng;
use crate::channel::punch::{NatInfo, NatType};
use crate::proto::message::PunchNatType;
use crate::channel::punch::{NatInfo, NatType, PunchModel};
use crate::channel::socket::LocalInterface;
#[cfg(feature = "upnp")]
use crate::util::UPnP;
mod stun;
@@ -47,12 +49,62 @@ pub fn local_ipv6_() -> io::Result<Ipv6Addr> {
pub fn local_ipv6() -> Option<Ipv6Addr> {
match local_ipv6_() {
Ok(ipv6) => Some(ipv6),
Ok(ipv6) => {
if is_ipv6_global(&ipv6) {
return Some(ipv6);
}
}
Err(e) => {
log::warn!("获取ipv6失败:{:?}", e);
None
}
}
None
}
pub const fn is_ipv4_global(ipv4: &Ipv4Addr) -> bool {
!(ipv4.octets()[0] == 0 // "This network"
|| ipv4.is_private()
|| ipv4.octets()[0] == 100 && (ipv4.octets()[1] & 0b1100_0000 == 0b0100_0000)//ipv4.is_shared()
|| ipv4.is_loopback()
|| ipv4.is_link_local()
// addresses reserved for future protocols (`192.0.0.0/24`)
// .9 and .10 are documented as globally reachable so they're excluded
|| (
ipv4.octets()[0] == 192 && ipv4.octets()[1] == 0 && ipv4.octets()[2] == 0
&& ipv4.octets()[3] != 9 && ipv4.octets()[3] != 10
)
|| ipv4.is_documentation()
|| ipv4.octets()[0] == 198 && (ipv4.octets()[1] & 0xfe) == 18//ipv4.is_benchmarking()
|| ipv4.octets()[0] & 240 == 240 && !ipv4.is_broadcast()//ipv4.is_reserved()
|| ipv4.is_broadcast())
}
pub const fn is_ipv6_global(ipv6addr: &Ipv6Addr) -> bool {
!(ipv6addr.is_unspecified()
|| ipv6addr.is_loopback()
// IPv4-mapped Address (`::ffff:0:0/96`)
|| matches!(ipv6addr.segments(), [0, 0, 0, 0, 0, 0xffff, _, _])
// IPv4-IPv6 Translat. (`64:ff9b:1::/48`)
|| matches!(ipv6addr.segments(), [0x64, 0xff9b, 1, _, _, _, _, _])
// Discard-Only Address Block (`100::/64`)
|| matches!(ipv6addr.segments(), [0x100, 0, 0, 0, _, _, _, _])
// IETF Protocol Assignments (`2001::/23`)
|| (matches!(ipv6addr.segments(), [0x2001, b, _, _, _, _, _, _] if b < 0x200)
&& !(
// Port Control Protocol Anycast (`2001:1::1`)
u128::from_be_bytes(ipv6addr.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0001
// Traversal Using Relays around NAT Anycast (`2001:1::2`)
|| u128::from_be_bytes(ipv6addr.octets()) == 0x2001_0001_0000_0000_0000_0000_0000_0002
// AMT (`2001:3::/32`)
|| matches!(ipv6addr.segments(), [0x2001, 3, _, _, _, _, _, _])
// AS112-v6 (`2001:4:112::/48`)
|| matches!(ipv6addr.segments(), [0x2001, 4, 0x112, _, _, _, _, _])
// ORCHIDv2 (`2001:20::/28`)
|| matches!(ipv6addr.segments(), [0x2001, b, _, _, _, _, _, _] if b >= 0x20 && b <= 0x2F)
))
|| (ipv6addr.segments()[0] == 0x2001) && (ipv6addr.segments()[1] == 0xdb8)//ipv6addr.is_documentation()
|| (ipv6addr.segments()[0] & 0xfe00) == 0xfc00//ipv6addr.is_unique_local()
|| (ipv6addr.segments()[0] & 0xffc0) == 0xfe80) //ipv6addr.is_unicast_link_local())
}
#[derive(Clone)]
@@ -62,38 +114,22 @@ pub struct NatTest {
time: Arc<AtomicCell<Instant>>,
udp_ports: Vec<u16>,
tcp_port: u16,
}
impl From<NatType> for PunchNatType {
fn from(value: NatType) -> Self {
match value {
NatType::Symmetric => PunchNatType::Symmetric,
NatType::Cone => PunchNatType::Cone,
}
}
}
impl Into<NatType> for PunchNatType {
fn into(self) -> NatType {
match self {
PunchNatType::Symmetric => NatType::Symmetric,
PunchNatType::Cone => NatType::Cone,
}
}
#[cfg(feature = "upnp")]
upnp: UPnP,
pub(crate) update_local_ipv4: bool,
}
impl NatTest {
pub fn new(
_channel_num: usize,
mut stun_server: Vec<String>,
stun_server: Vec<String>,
local_ipv4: Option<Ipv4Addr>,
ipv6: Option<Ipv6Addr>,
udp_ports: Vec<u16>,
tcp_port: u16,
update_local_ipv4: bool,
punch_model: PunchModel,
) -> NatTest {
if stun_server.len() > 5 {
stun_server.truncate(5);
}
let ports = vec![0; udp_ports.len()];
let nat_info = NatInfo::new(
Vec::new(),
@@ -103,17 +139,33 @@ impl NatTest {
ipv6,
udp_ports.clone(),
tcp_port,
0,
NatType::Cone,
punch_model,
);
let info = Arc::new(Mutex::new(nat_info));
#[cfg(feature = "upnp")]
let upnp = UPnP::default();
#[cfg(feature = "upnp")]
for port in &udp_ports {
upnp.add_udp_port(*port);
}
#[cfg(feature = "upnp")]
upnp.add_tcp_port(tcp_port);
let instant = Instant::now();
NatTest {
stun_server,
info,
time: Arc::new(AtomicCell::new(
Instant::now().sub(Duration::from_secs(100)),
instant
.checked_sub(Duration::from_secs(100))
.unwrap_or(instant),
)),
udp_ports,
tcp_port,
#[cfg(feature = "upnp")]
upnp,
update_local_ipv4,
}
}
pub fn can_update(&self) -> bool {
@@ -185,25 +237,49 @@ impl NatTest {
}
false
}
pub fn update_addr(&self, index: usize, ip: Ipv4Addr, port: u16) {
pub fn update_addr(&self, index: usize, ip: Ipv4Addr, port: u16) -> bool {
let mut guard = self.info.lock();
guard.update_addr(index, ip, port)
}
pub fn update_tcp_port(&self, port: u16) {
let mut guard = self.info.lock();
guard.update_tcp_port(port)
}
pub fn re_test(
&self,
local_ipv4: Option<Ipv4Addr>,
ipv6: Option<Ipv6Addr>,
) -> io::Result<NatInfo> {
let (nat_type, public_ips, port_range) = stun::stun_test_nat(self.stun_server.clone())?;
default_interface: &LocalInterface,
) -> anyhow::Result<NatInfo> {
let mut stun_server = self.stun_server.clone();
if stun_server.len() > 5 {
stun_server.shuffle(&mut rand::thread_rng());
stun_server.truncate(5);
log::info!("stun_server truncate {:?}", stun_server);
}
let (nat_type, public_ips, port_range) =
stun::stun_test_nat(stun_server, default_interface)?;
if public_ips.is_empty() {
Err(anyhow!("public_ips.is_empty"))?
}
let mut guard = self.info.lock();
guard.nat_type = nat_type;
guard.public_ips = public_ips;
guard.public_port_range = port_range;
guard.local_ipv4 = local_ipv4;
if local_ipv4.is_some() {
guard.local_ipv4 = local_ipv4;
}
guard.ipv6 = ipv6;
Ok(guard.clone())
}
#[cfg(feature = "upnp")]
pub fn reset_upnp(&self) {
let local_ipv4 = self.info.lock().local_ipv4.clone();
if let Some(local_ipv4) = local_ipv4 {
self.upnp.reset(local_ipv4)
}
}
pub fn send_data(&self) -> anyhow::Result<(Vec<u8>, SocketAddr)> {
let len = self.stun_server.len();
let stun_server = if len == 1 {
@@ -246,7 +322,7 @@ impl NatTest {
let source_ip = match source_addr.ip() {
IpAddr::V4(ip) => ip,
IpAddr::V6(ip) => {
if let Some(ip) = ip.to_ipv4_mapped() {
if let Some(ip) = ip.to_ipv4() {
ip
} else {
return Ok(());
@@ -266,14 +342,10 @@ impl NatTest {
}
}
if !check_fail {
let ip = addr.ip();
if !ip.is_multicast()
&& !ip.is_broadcast()
&& !ip.is_unspecified()
&& !ip.is_loopback()
&& !ip.is_private()
{
self.update_addr(index, *addr.ip(), addr.port());
if is_ipv4_global(addr.ip()) {
if self.update_addr(index, *addr.ip(), addr.port()) {
log::info!("回应地址{:?},来源stun {:?}", addr, source_addr)
}
}
}
}
+19 -14
View File
@@ -4,22 +4,21 @@ use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::time::Duration;
use crate::channel::punch::NatType;
use crate::channel::socket::{bind_udp, LocalInterface};
use rand::RngCore;
use std::net::UdpSocket;
use stun_format::Attr;
pub fn stun_test_nat(stun_servers: Vec<String>) -> io::Result<(NatType, Vec<Ipv4Addr>, u16)> {
let mut th = Vec::new();
for _ in 0..2 {
let stun_servers = stun_servers.clone();
let handle = std::thread::spawn(move || stun_test_nat0(stun_servers));
th.push(handle);
}
pub fn stun_test_nat(
stun_servers: Vec<String>,
default_interface: &LocalInterface,
) -> anyhow::Result<(NatType, Vec<Ipv4Addr>, u16)> {
let mut nat_type = NatType::Cone;
let mut port_range = 0;
let mut hash_set = HashSet::new();
for x in th {
match x.join().unwrap() {
for _ in 0..2 {
let stun_servers = stun_servers.clone();
match stun_test_nat0(stun_servers, default_interface) {
Ok((nat_type_t, ip_list_t, port_range_t)) => {
if nat_type_t == NatType::Symmetric {
nat_type = NatType::Symmetric;
@@ -39,8 +38,13 @@ pub fn stun_test_nat(stun_servers: Vec<String>) -> io::Result<(NatType, Vec<Ipv4
Ok((nat_type, hash_set.into_iter().collect(), port_range))
}
pub fn stun_test_nat0(stun_servers: Vec<String>) -> io::Result<(NatType, Vec<Ipv4Addr>, u16)> {
let udp = UdpSocket::bind("0.0.0.0:0")?;
pub fn stun_test_nat0(
stun_servers: Vec<String>,
default_interface: &LocalInterface,
) -> anyhow::Result<(NatType, Vec<Ipv4Addr>, u16)> {
let udp = bind_udp("0.0.0.0:0".parse().unwrap(), default_interface)?;
udp.set_nonblocking(false)?;
let udp: UdpSocket = udp.into();
udp.set_read_timeout(Some(Duration::from_millis(500)))?;
let mut nat_type = NatType::Cone;
let mut min_port = u16::MAX;
@@ -86,13 +90,13 @@ fn test_nat(udp: &UdpSocket, stun_server: &String) -> io::Result<HashSet<SocketA
udp.connect(stun_server)?;
let tid = rand::thread_rng().next_u64() as u128;
let mut addr = HashSet::new();
let (mapped_addr1, changed_addr1) = test_nat_(&udp, true, true, tid)?;
let (mapped_addr1, changed_addr1) = test_nat_(&udp, stun_server, true, true, tid)?;
if mapped_addr1.is_ipv4() {
addr.insert(mapped_addr1);
}
if let Some(changed_addr1) = changed_addr1 {
if udp.connect(changed_addr1).is_ok() {
match test_nat_(&udp, false, false, tid + 1) {
match test_nat_(&udp, stun_server, false, false, tid + 1) {
Ok((mapped_addr2, _)) => {
if mapped_addr2.is_ipv4() {
addr.insert(mapped_addr1);
@@ -116,6 +120,7 @@ fn test_nat(udp: &UdpSocket, stun_server: &String) -> io::Result<HashSet<SocketA
fn test_nat_(
udp: &UdpSocket,
stun_server: &String,
change_ip: bool,
change_port: bool,
tid: u128,
@@ -134,7 +139,7 @@ fn test_nat_(
let (len, _addr) = match udp.recv_from(&mut buf) {
Ok(rs) => rs,
Err(e) => {
log::warn!("stun error {:?}", e);
log::warn!("stun {} error {:?}", stun_server, e);
continue;
}
};
+1
View File
@@ -32,6 +32,7 @@ async fn tcp_mapping_(
}
async fn copy(source_tcp: TcpStream, destination: &String) -> anyhow::Result<()> {
// 或许这里也应该绑定最匹配的网卡,不然全局代理会影响映射
let dest_tcp = TcpStream::connect(destination)
.await
.with_context(|| format!("TCP connection target failed {:?}", destination))?;
+8 -3
View File
@@ -1,9 +1,12 @@
#![allow(dead_code)]
use std::io;
use std::net::Ipv4Addr;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Protocol {
Ipv4,
WGIpv4,
Ipv4Broadcast,
Unknown(u8),
}
@@ -12,16 +15,18 @@ impl From<u8> for Protocol {
fn from(value: u8) -> Self {
match value {
4 => Protocol::Ipv4,
5 => Protocol::WGIpv4,
201 => Protocol::Ipv4Broadcast,
val => Protocol::Unknown(val),
}
}
}
impl Into<u8> for Protocol {
fn into(self) -> u8 {
match self {
impl From<Protocol> for u8 {
fn from(val: Protocol) -> Self {
match val {
Protocol::Ipv4 => 4,
Protocol::WGIpv4 => 5,
Protocol::Ipv4Broadcast => 201,
Protocol::Unknown(val) => val,
}
+3 -5
View File
@@ -128,11 +128,10 @@ impl<B: AsRef<[u8]>> NetPacket<B> {
"length overflow",
));
}
// 不能大于udp最大载荷长度
if data_len < 12 || data_len > 65535 - 20 - 8 {
if data_len < 12 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"length overflow",
"data_len too short",
));
}
Ok(NetPacket { data_len, buffer })
@@ -215,8 +214,7 @@ impl<B: AsRef<[u8]> + AsMut<[u8]>> NetPacket<B> {
}
pub fn set_gateway_flag(&mut self, is_gateway: bool) {
if is_gateway {
// 后面的版本再改为0x40,改了之后不兼容1.2.5之前的版本
self.buffer.as_mut()[0] = self.buffer.as_ref()[0] | 0x50
self.buffer.as_mut()[0] = self.buffer.as_ref()[0] | 0x40
} else {
self.buffer.as_mut()[0] = self.buffer.as_ref()[0] & 0xBF
};
+14 -4
View File
@@ -1,4 +1,4 @@
use crate::{DeviceConfig, ErrorInfo, ErrorType};
use crate::{DeviceConfig, ErrorInfo, ErrorType, VntCallback};
use std::io;
use std::net::Ipv4Addr;
use std::sync::Arc;
@@ -10,12 +10,15 @@ const DEFAULT_TUN_NAME: &str = "vnt-tun";
#[cfg(target_os = "windows")]
const DEFAULT_TAP_NAME: &str = "vnt-tap";
pub fn create_device(config: DeviceConfig) -> Result<Arc<Device>, ErrorInfo> {
pub fn create_device<Call: VntCallback>(
config: DeviceConfig,
call: &Call,
) -> Result<Arc<Device>, ErrorInfo> {
let device = match create_device0(&config) {
Ok(device) => device,
Err(e) => {
return Err(ErrorInfo::new_msg(
ErrorType::Unknown,
ErrorType::FailedToCrateDevice,
format!("create device {:?}", e),
));
}
@@ -44,7 +47,14 @@ pub fn create_device(config: DeviceConfig) -> Result<Arc<Device>, ErrorInfo> {
for (dest, mask) in config.external_route {
if let Err(e) = device.add_route(dest, mask, 1) {
log::warn!("添加路由失败 ={:?}", e);
log::warn!("添加路由失败,请检查-i参数是否和现有路由冲突 ={:?}", e);
call.error(ErrorInfo::new_msg(
ErrorType::Warn,
format!(
"警告! 添加路由失败,请检查-i参数是否和现有路由冲突 ={:?}",
e
),
))
}
}
Ok(device)
+10 -11
View File
@@ -1,4 +1,6 @@
use std::collections::HashMap;
use std::io;
use std::net::Ipv4Addr;
use std::sync::Arc;
use crossbeam_utils::atomic::AtomicCell;
@@ -16,7 +18,7 @@ use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
#[cfg(feature = "ip_proxy")]
use crate::ip_proxy::IpProxyMap;
use crate::tun_tap_device::vnt_device::DeviceWrite;
use crate::util::{SingleU64Adder, StopManager};
use crate::util::StopManager;
#[repr(transparent)]
#[derive(Clone, Default)]
@@ -67,8 +69,7 @@ struct TunDeviceHelperInner {
ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
up_counter: SingleU64Adder,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
compressor: Compressor,
}
@@ -81,8 +82,7 @@ impl TunDeviceHelper {
#[cfg(feature = "ip_proxy")] ip_proxy_map: Option<IpProxyMap>,
client_cipher: Cipher,
server_cipher: Cipher,
up_counter: SingleU64Adder,
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
device_map: Arc<Mutex<(u16, HashMap<Ipv4Addr, PeerDeviceInfo>)>>,
compressor: Compressor,
device_adapter: DeviceAdapter,
) -> Self {
@@ -95,8 +95,7 @@ impl TunDeviceHelper {
ip_proxy_map,
client_cipher,
server_cipher,
up_counter,
device_list,
device_map,
compressor,
};
Self {
@@ -113,14 +112,14 @@ impl TunDeviceHelper {
device_stop.stop();
std::thread::sleep(std::time::Duration::from_millis(300));
//确保停止了
if device_stop.is_stop() {
if device_stop.is_stopped() {
break;
}
}
}
}
/// 要保证先stop 再start
pub fn start(&self, device: Arc<Device>) -> io::Result<()> {
pub fn start(&self, device: Arc<Device>, allow_wire_guard: bool) -> io::Result<()> {
self.device_adapter.insert(device.clone());
let device_stop = DeviceStop::default();
let s = self.device_stop.lock().replace(device_stop.clone());
@@ -136,10 +135,10 @@ impl TunDeviceHelper {
inner.ip_proxy_map,
inner.client_cipher,
inner.server_cipher,
inner.up_counter,
inner.device_list,
inner.device_map,
inner.compressor,
device_stop,
allow_wire_guard,
)
}
}
+9 -115
View File
@@ -1,139 +1,33 @@
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
/// 不安全的并发计数器,谨慎使用
use crossbeam_utils::atomic::AtomicCell;
#[derive(Clone, Default)]
pub struct U64Adder {
global_index: Arc<AtomicUsize>,
inner: Arc<U64AdderInner>,
index: usize,
}
#[derive(Clone)]
pub struct SingleU64Adder {
inner: Arc<SingleU64AdderInner>,
}
impl SingleU64Adder {
pub fn new() -> Self {
Self {
inner: Arc::new(SingleU64AdderInner::new()),
}
}
pub fn add(&mut self, num: u64) {
self.inner.add(num);
}
pub fn get(&self) -> u64 {
self.inner.get()
}
pub fn watch(&self) -> WatchSingleU64Adder {
WatchSingleU64Adder {
inner: self.inner.clone(),
}
}
}
struct SingleU64AdderInner {
ptr: *mut u64,
}
impl SingleU64AdderInner {
fn new() -> Self {
Self {
ptr: Box::into_raw(Box::new(0)),
}
}
#[inline(always)]
fn add(&self, num: u64) {
unsafe { *self.ptr += num }
}
fn get(&self) -> u64 {
unsafe { *self.ptr }
}
}
impl Drop for SingleU64AdderInner {
fn drop(&mut self) {
unsafe {
let _ = Box::from_raw(self.ptr);
}
}
}
unsafe impl Send for SingleU64AdderInner {}
unsafe impl Sync for SingleU64AdderInner {}
struct U64AdderInner {
base: Vec<SingleU64AdderInner>,
}
impl U64AdderInner {
pub fn get(&self) -> u64 {
let mut count = 0;
for counter in self.base.iter() {
count += counter.get()
}
count
}
count: Arc<AtomicCell<u64>>,
}
impl U64Adder {
/// 计数槽容量
pub fn with_capacity(capacity: usize) -> Self {
let mut base = Vec::with_capacity(capacity);
for _ in 0..capacity {
base.push(SingleU64AdderInner::new())
}
let inner = Arc::new(U64AdderInner { base });
U64Adder {
global_index: Arc::new(AtomicUsize::new(1)),
inner,
index: 0,
}
}
pub fn add(&mut self, num: u64) {
self.inner.base[self.index].add(num);
pub fn add(&self, num: u64) {
self.count.fetch_add(num);
}
pub fn get(&self) -> u64 {
self.inner.get()
self.count.load()
}
pub fn watch(&self) -> WatchU64Adder {
WatchU64Adder {
inner: self.inner.clone(),
}
}
}
impl Clone for U64Adder {
fn clone(&self) -> Self {
let index = self.global_index.fetch_add(1, Ordering::AcqRel);
if index > self.inner.base.len() {
panic!()
}
Self {
global_index: self.global_index.clone(),
inner: self.inner.clone(),
index,
count: self.count.clone(),
}
}
}
#[derive(Clone)]
pub struct WatchU64Adder {
inner: Arc<U64AdderInner>,
count: Arc<AtomicCell<u64>>,
}
impl WatchU64Adder {
pub fn get(&self) -> u64 {
self.inner.get()
}
}
#[derive(Clone)]
pub struct WatchSingleU64Adder {
inner: Arc<SingleU64AdderInner>,
}
impl WatchSingleU64Adder {
pub fn get(&self) -> u64 {
self.inner.get()
self.count.load()
}
}
+36 -15
View File
@@ -5,6 +5,7 @@ use std::str::FromStr;
use std::time::Duration;
use std::{io, thread};
use crate::channel::socket::LocalInterface;
use anyhow::Context;
use dns_parser::{Builder, Packet, QueryClass, QueryType, RData, ResponseCode};
@@ -79,6 +80,7 @@ fn address_choose0(addrs: Vec<SocketAddr>) -> anyhow::Result<SocketAddr> {
pub fn dns_query_all(
domain: &str,
mut name_servers: Vec<String>,
default_interface: &LocalInterface,
) -> anyhow::Result<Vec<SocketAddr>> {
match SocketAddr::from_str(domain) {
Ok(addr) => Ok(vec![addr]),
@@ -102,7 +104,7 @@ pub fn dns_query_all(
let mut err: Option<anyhow::Error> = None;
for name_server in name_servers {
if let Some(domain) = txt_domain.as_ref() {
match txt_dns(domain, name_server) {
match txt_dns(domain, name_server, default_interface) {
Ok(addr) => {
if !addr.is_empty() {
return Ok(addr);
@@ -127,12 +129,14 @@ pub fn dns_query_all(
let th1 = {
let host = host.to_string();
let name_server = name_server.clone();
thread::spawn(move || a_dns(host, name_server))
let default_interface = default_interface.clone();
thread::spawn(move || a_dns(host, name_server, &default_interface))
};
let th2 = {
let host = host.to_string();
let name_server = name_server.clone();
thread::spawn(move || aaaa_dns(host, name_server))
let default_interface = default_interface.clone();
thread::spawn(move || aaaa_dns(host, name_server, &default_interface))
};
let mut addr = Vec::new();
match th1.join().unwrap() {
@@ -230,9 +234,13 @@ fn query<'a>(
Ok(pkt)
}
pub fn txt_dns(domain: &str, name_server: String) -> anyhow::Result<Vec<SocketAddr>> {
pub fn txt_dns(
domain: &str,
name_server: String,
default_interface: &LocalInterface,
) -> anyhow::Result<Vec<SocketAddr>> {
let name_server: SocketAddr = name_server.parse()?;
let udp = bind_udp(name_server)?;
let udp = bind_udp(name_server, default_interface)?;
let mut buf = [0; 65536];
let message = query(&udp, domain, name_server, QueryType::TXT, &mut buf)?;
let mut rs = Vec::new();
@@ -249,19 +257,28 @@ pub fn txt_dns(domain: &str, name_server: String) -> anyhow::Result<Vec<SocketAd
Ok(rs)
}
fn bind_udp(name_server: SocketAddr) -> anyhow::Result<UdpSocket> {
let udp = if name_server.is_ipv4() {
UdpSocket::bind("0.0.0.0:0")?
fn bind_udp(
name_server: SocketAddr,
default_interface: &LocalInterface,
) -> anyhow::Result<UdpSocket> {
let addr: SocketAddr = if name_server.is_ipv4() {
"0.0.0.0:0".parse().unwrap()
} else {
UdpSocket::bind("[::]:0")?
"[::]:0".parse().unwrap()
};
udp.set_read_timeout(Some(Duration::from_millis(800)))?;
Ok(udp)
let socket = crate::channel::socket::bind_udp(addr, default_interface)?;
socket.set_nonblocking(false)?;
socket.set_read_timeout(Some(Duration::from_millis(800)))?;
Ok(socket.into())
}
pub fn a_dns(domain: String, name_server: String) -> anyhow::Result<Vec<Ipv4Addr>> {
pub fn a_dns(
domain: String,
name_server: String,
default_interface: &LocalInterface,
) -> anyhow::Result<Vec<Ipv4Addr>> {
let name_server: SocketAddr = name_server.parse()?;
let udp = bind_udp(name_server)?;
let udp = bind_udp(name_server, default_interface)?;
let mut buf = [0; 65536];
let message = query(&udp, &domain, name_server, QueryType::A, &mut buf)?;
let mut rs = Vec::new();
@@ -273,9 +290,13 @@ pub fn a_dns(domain: String, name_server: String) -> anyhow::Result<Vec<Ipv4Addr
Ok(rs)
}
pub fn aaaa_dns(domain: String, name_server: String) -> anyhow::Result<Vec<Ipv6Addr>> {
pub fn aaaa_dns(
domain: String,
name_server: String,
default_interface: &LocalInterface,
) -> anyhow::Result<Vec<Ipv6Addr>> {
let name_server: SocketAddr = name_server.parse()?;
let udp = bind_udp(name_server)?;
let udp = bind_udp(name_server, default_interface)?;
let mut buf = [0; 65536];
let message = query(&udp, &domain, name_server, QueryType::AAAA, &mut buf)?;
let mut rs = Vec::new();
+5
View File
@@ -0,0 +1,5 @@
mod rate_limiter;
pub use rate_limiter::*;
mod traffic_meter;
pub use traffic_meter::*;
+62
View File
@@ -0,0 +1,62 @@
use parking_lot::Mutex;
use std::sync::Arc;
use std::time::Instant;
#[derive(Clone)]
pub struct ConcurrentRateLimiter {
inner: Arc<Mutex<RateLimiter>>,
}
impl ConcurrentRateLimiter {
pub fn new(capacity: usize, refill_rate: usize) -> Self {
let inner = RateLimiter::new(capacity, refill_rate);
Self {
inner: Arc::new(Mutex::new(inner)),
}
}
pub fn try_acquire(&self) -> bool {
self.inner.lock().try_acquire()
}
}
pub struct RateLimiter {
capacity: usize,
tokens: usize,
refill_rate: usize,
last_refill: Instant,
}
impl RateLimiter {
// 初始化限流器
pub fn new(capacity: usize, refill_rate: usize) -> Self {
Self {
capacity,
tokens: capacity,
refill_rate,
last_refill: Instant::now(),
}
}
// 尝试获取一个令牌
pub fn try_acquire(&mut self) -> bool {
self.refill();
if self.tokens > 0 {
self.tokens -= 1;
true
} else {
false
}
}
// 补充令牌
fn refill(&mut self) {
let now = Instant::now();
let elapsed = now.duration_since(self.last_refill).as_secs() as usize;
let new_tokens = elapsed * self.refill_rate;
if new_tokens > 0 {
self.tokens = std::cmp::min(self.capacity, self.tokens + new_tokens);
self.last_refill = now;
}
}
}
+132
View File
@@ -0,0 +1,132 @@
use parking_lot::Mutex;
use std::collections::{HashMap, VecDeque};
use std::net::Ipv4Addr;
use std::sync::Arc;
use std::time::{Duration, Instant};
#[derive(Clone)]
pub struct TrafficMeterMultiAddress {
history_capacity: usize,
inner: Arc<Mutex<(u64, HashMap<Ipv4Addr, TrafficMeter>)>>,
}
impl Default for TrafficMeterMultiAddress {
fn default() -> Self {
TrafficMeterMultiAddress::new(100)
}
}
impl TrafficMeterMultiAddress {
pub fn new(history_capacity: usize) -> Self {
let inner = Arc::new(Mutex::new((0, HashMap::new())));
Self {
inner,
history_capacity,
}
}
pub fn add_traffic(&self, ip: Ipv4Addr, amount: usize) {
let mut guard = self.inner.lock();
guard.0 += amount as u64;
guard
.1
.entry(ip)
.or_insert(TrafficMeter::new(self.history_capacity))
.add_traffic(amount)
}
pub fn total(&self) -> u64 {
self.inner.lock().0
}
pub fn get_all(&self) -> (u64, HashMap<Ipv4Addr, u64>) {
let guard = self.inner.lock();
(
guard.0,
guard.1.iter().map(|(ip, t)| (*ip, t.total())).collect(),
)
}
pub fn get_all_history(&self) -> (u64, HashMap<Ipv4Addr, (u64, Vec<usize>)>) {
let guard = self.inner.lock();
(
guard.0,
guard
.1
.iter()
.map(|(ip, t)| (*ip, (t.total(), t.get_history())))
.collect(),
)
}
pub fn get_history(&self, ip: &Ipv4Addr) -> Option<(u64, Vec<usize>)> {
self.inner
.lock()
.1
.get(ip)
.map(|t| (t.total(), t.get_history()))
}
}
#[derive(Clone)]
pub struct ConcurrentTrafficMeter {
inner: Arc<Mutex<TrafficMeter>>,
}
impl ConcurrentTrafficMeter {
pub fn new(history_capacity: usize) -> Self {
let inner = Arc::new(Mutex::new(TrafficMeter::new(history_capacity)));
Self { inner }
}
pub fn add_traffic(&self, amount: usize) {
self.inner.lock().add_traffic(amount)
}
pub fn get_history(&self) -> Vec<usize> {
self.inner.lock().get_history()
}
}
pub struct TrafficMeter {
start_time: Instant,
total: u64,
count: usize,
history_capacity: usize,
history: VecDeque<usize>,
}
impl TrafficMeter {
// 初始化一个新的 TrafficMeter
pub fn new(history_capacity: usize) -> Self {
Self {
start_time: Instant::now(),
total: 0,
count: 0,
history: VecDeque::with_capacity(history_capacity),
history_capacity,
}
}
// 增加流量计数
pub fn add_traffic(&mut self, amount: usize) {
self.total += amount as u64;
self.count += amount;
self.check_time();
}
// 检查时间是否超过一秒,如果是,记录流量并重置计数器和时间
fn check_time(&mut self) {
if self.start_time.elapsed() >= Duration::new(1, 0) {
// 将当前计数添加到历史记录
if self.history.len() >= self.history_capacity {
self.history.pop_front(); // 保持历史记录不超过capacity
}
self.history.push_back(self.count);
// 重置计数器和时间
self.count = 0;
self.start_time = Instant::now();
}
}
pub fn total(&self) -> u64 {
self.total
}
// 获取流量记录
pub fn get_history(&self) -> Vec<usize> {
self.history.iter().cloned().collect()
}
}
+9 -2
View File
@@ -3,8 +3,15 @@ mod scheduler;
pub use notify::{StopManager, Worker};
pub use scheduler::Scheduler;
mod counter;
pub use counter::*;
// mod counter;
// pub use counter::*;
mod dns_query;
pub use dns_query::*;
#[cfg(feature = "upnp")]
mod upnp;
#[cfg(feature = "upnp")]
pub use upnp::*;
pub mod limit;
+26 -9
View File
@@ -28,7 +28,7 @@ impl StopManager {
self.inner.add_listener(name, f)
}
pub fn stop(&self) {
self.inner.stop("");
self.inner.stop();
}
pub fn wait(&self) {
self.inner.wait();
@@ -36,8 +36,8 @@ impl StopManager {
pub fn wait_timeout(&self, dur: Duration) -> bool {
self.inner.wait_timeout(dur)
}
pub fn is_stop(&self) -> bool {
self.inner.state.load(Ordering::Acquire)
pub fn is_stopped(&self) -> bool {
self.inner.is_stopped()
}
}
@@ -81,17 +81,17 @@ impl StopManagerInner {
guard.1.push((name.clone(), Box::new(f)));
Ok(Worker::new(name, self.clone()))
}
fn stop(&self, skip_name: &str) {
fn stop(&self) {
self.state.store(true, Ordering::Release);
let mut guard = self.listeners.lock();
guard.0 = true;
for (name, listener) in guard.1.drain(..) {
if &name == skip_name {
continue;
}
for (_name, listener) in guard.1.drain(..) {
listener();
}
}
pub fn is_stopped(&self) -> bool {
self.worker_num.load(Ordering::Acquire) == 0
}
fn wait(&self) {
{
let mut guard = self.park_threads.lock();
@@ -118,6 +118,7 @@ impl StopManagerInner {
self.worker_num.load(Ordering::Acquire) == 0
}
fn stop_call(&self) {
self.stop();
if let Some(call) = self.stop_call.lock().take() {
call();
}
@@ -136,6 +137,19 @@ impl Worker {
}
fn release0(&self) {
let inner = &self.inner;
let worker_name = &self.name;
{
let mut mutex_guard = inner.listeners.lock();
if let Some(pos) = mutex_guard
.1
.iter()
.position(|(name, _)| name == worker_name)
{
let (_, listener) = mutex_guard.1.remove(pos);
listener();
}
}
let count = inner.worker_num.fetch_sub(1, Ordering::AcqRel);
if count == 1 {
for x in inner.park_threads.lock().drain(..) {
@@ -145,7 +159,10 @@ impl Worker {
}
}
pub fn stop_all(self) {
self.inner.stop(&self.name)
self.inner.stop()
}
pub fn stop_self(self) {
drop(self)
}
}
+52 -7
View File
@@ -1,5 +1,8 @@
use crate::util::StopManager;
use crossbeam_utils::atomic::AtomicCell;
use std::collections::BinaryHeap;
use std::sync::mpsc::TrySendError;
use std::sync::Arc;
use std::{
cmp::Ordering,
sync::mpsc::{sync_channel, Receiver, SyncSender},
@@ -10,45 +13,62 @@ struct DelayedTask {
f: Box<dyn FnOnce(&Scheduler) + Send>,
next: Instant,
}
impl Eq for DelayedTask {}
impl PartialEq for DelayedTask {
fn eq(&self, other: &Self) -> bool {
self.next.eq(&other.next)
}
}
impl PartialOrd for DelayedTask {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.next.partial_cmp(&other.next).map(|ord| ord.reverse())
}
}
impl Ord for DelayedTask {
fn cmp(&self, other: &Self) -> Ordering {
self.next.cmp(&other.next).reverse()
}
}
enum Op {
Task(DelayedTask),
Stop,
}
#[derive(Clone)]
pub struct Scheduler {
sender: SyncSender<Op>,
state: Arc<AtomicCell<SchedulerState>>,
}
#[derive(Copy, Clone, Eq, PartialEq)]
enum SchedulerState {
Running,
ShutdownNow, // 立即停止任务执行,队列中剩余的任务不再执行
_Shutdown, //执行完队列中剩余的任务再停止
}
impl Scheduler {
pub fn new(stop_manager: StopManager) -> anyhow::Result<Self> {
let (sender, receiver) = sync_channel::<Op>(32);
let s = Self { sender };
let state = Arc::new(AtomicCell::new(SchedulerState::Running));
let s = Self { sender, state };
let s_inner = s.clone();
let worker = {
let scheduler = s.clone();
stop_manager.add_listener("Scheduler".into(), move || {
scheduler.shutdown();
scheduler.shutdown_now();
})?
};
std::thread::Builder::new()
.name("Scheduler".into())
.spawn(move || {
run(receiver, s_inner);
run(receiver, &s_inner);
s_inner.shutdown_now();
worker.stop_all();
})
.expect("Scheduler");
@@ -58,20 +78,44 @@ impl Scheduler {
where
F: FnOnce(&Scheduler) + Send + 'static,
{
if self.state.load() != SchedulerState::Running {
log::error!("定时任务执行停止");
return false;
}
let task = DelayedTask {
f: Box::new(f),
next: Instant::now().checked_add(time).unwrap(),
};
self.sender.send(Op::Task(task)).is_ok()
// 如果是任务中调用此方法,那这里用send可能会导致整个定时任务阻塞
// 任务总数不能大于或等于通道长度,所以改成try_send快速失败
match self.sender.try_send(Op::Task(task)) {
Ok(_) => true,
Err(e) => {
match e {
TrySendError::Full(_) => {
log::error!("定时任务队列达到上限");
}
TrySendError::Disconnected(_) => {
log::error!("定时任务执行停止 通道关闭");
}
}
false
}
}
}
pub fn shutdown(self) {
pub fn shutdown_now(&self) {
self.state.store(SchedulerState::ShutdownNow);
let _ = self.sender.send(Op::Stop);
}
}
fn run(receiver: Receiver<Op>, s_inner: Scheduler) {
fn run(receiver: Receiver<Op>, s_inner: &Scheduler) {
let mut binary_heap = BinaryHeap::<DelayedTask>::with_capacity(32);
loop {
while let Some(task) = binary_heap.peek() {
if s_inner.state.load() == SchedulerState::ShutdownNow {
return;
}
let now = Instant::now();
if now < task.next {
//需要等待对应时间
@@ -89,7 +133,7 @@ fn run(receiver: Receiver<Op>, s_inner: Scheduler) {
}
} else {
if let Some(task) = binary_heap.pop() {
(task.f)(&s_inner);
(task.f)(s_inner);
}
}
}
@@ -120,6 +164,7 @@ fn run(receiver: Receiver<Op>, s_inner: Scheduler) {
}
}
}
fn add_task(op: Op, binary_heap: &mut BinaryHeap<DelayedTask>) -> bool {
return match op {
Op::Task(task) => {
+81
View File
@@ -0,0 +1,81 @@
use igd::{search_gateway, PortMappingProtocol};
use std::net::{Ipv4Addr, SocketAddrV4};
use std::ops::Deref;
use std::sync::Arc;
use parking_lot::Mutex;
#[derive(Clone, Default)]
pub struct UPnP {
inner: Arc<UpnpInner>,
}
impl Deref for UPnP {
type Target = UpnpInner;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
#[derive(Default)]
pub struct UpnpInner {
list: Mutex<Vec<(PortMappingProtocol, u16)>>,
}
impl UpnpInner {
pub fn add_tcp_port(&self, port: u16) {
self.list.lock().push((PortMappingProtocol::TCP, port));
}
pub fn add_udp_port(&self, port: u16) {
self.list.lock().push((PortMappingProtocol::UDP, port));
}
pub fn reset(&self, local_ip: Ipv4Addr) {
let gateway = match search_gateway(Default::default()) {
Ok(gateway) => gateway,
Err(e) => {
log::warn!("search_gateway {:?}", e);
return;
}
};
let guard = self.list.lock();
// 不支持upnp的情况会阻塞30秒,之后再改这个库
for (protocol, port) in guard.iter() {
let local_addr = SocketAddrV4::new(local_ip, *port);
log::info!("add upnp protocol={} {}", protocol, local_addr);
if let Err(e) = gateway.add_port(*protocol, *port, local_addr, 700, "upnp") {
log::warn!(
"add upnp failed protocol={},port={} err:{:?}",
protocol,
port,
e
);
}
}
}
}
impl Drop for UpnpInner {
fn drop(&mut self) {
// let gateway = match search_gateway(Default::default()) {
// Ok(gateway) => gateway,
// Err(e) => {
// log::warn!("search_gateway {:?}", e);
// return;
// }
// };
//
// let guard = self.list.lock();
// for (protocol, port) in guard.iter() {
// if let Err(e) = gateway.remove_port(*protocol, *port) {
// log::warn!(
// "remove upnp failed protocol={},port={} err:{:?}",
// protocol,
// port,
// e
// );
// }
// }
}
}
+5 -3
View File
@@ -11,6 +11,7 @@ libc = "0.2.153"
log = { version = "0.4.20", features = [] }
rand = "0.8.5"
sha2 = { version = "0.10.6", features = ["oid"] }
[target.'cfg(any(target_os = "linux", target_os = "macos"))'.dependencies]
ioctl = { version = "0.8", package = "ioctl-sys" }
@@ -18,15 +19,16 @@ ioctl = { version = "0.8", package = "ioctl-sys" }
[target.'cfg(target_os = "windows")'.dependencies]
libloading = "0.8.0"
widestring = "1.0.2"
winapi = {version = "0.3",features = [
winapi = { version = "0.3", features = [
"errhandlingapi",
"libloaderapi",
"combaseapi",
"ioapiset",
"winioctl",
"setupapi",
"synchapi",
"netioapi",
"fileapi","handleapi","winerror","minwindef","ifdef","basetsd","winnt","winreg","winbase","minwinbase",
"fileapi", "handleapi", "winerror", "minwindef", "ifdef", "basetsd", "winnt", "winreg", "winbase", "minwinbase",
"impl-default"
]}
] }
+10 -1
View File
@@ -4,7 +4,16 @@ use std::net::Ipv4Addr;
use crate::unix::exe_cmd;
pub fn add_route(name: &str, address: Ipv4Addr, netmask: Ipv4Addr) -> io::Result<()> {
let cmd = format!("ip route add {:?}/{:?} dev {}", address, netmask, name);
let cmd = if netmask.is_broadcast() {
format!("route add -host {:?} {}", address, name)
} else {
format!(
"route add -net {}/{} {}",
address,
u32::from(netmask).count_ones(),
name
)
};
exe_cmd(&cmd)?;
Ok(())
}
+167
View File
@@ -0,0 +1,167 @@
use libloading::Library;
use std::ffi::{c_char, CStr, CString};
use std::fs::File;
use std::io::{self, Read, Seek};
use std::path::PathBuf;
use winapi::shared::minwindef::HINSTANCE;
use winapi::um::libloaderapi::{GetModuleFileNameA, GetModuleHandleA};
#[repr(C)]
#[derive(Debug)]
struct DosHeader {
e_magic: u16,
e_cblp: u16,
e_cp: u16,
e_crlc: u16,
e_cparhdr: u16,
e_minalloc: u16,
e_maxalloc: u16,
e_ss: u16,
e_sp: u16,
e_csum: u16,
e_ip: u16,
e_cs: u16,
e_lfarlc: u16,
e_ovno: u16,
e_res: [u16; 4],
e_oemid: u16,
e_oeminfo: u16,
e_res2: [u16; 10],
e_lfanew: i32,
}
#[repr(C)]
#[derive(Debug)]
struct FileHeader {
machine: u16,
number_of_sections: u16,
time_date_stamp: u32,
pointer_to_symbol_table: u32,
number_of_symbols: u32,
size_of_optional_header: u16,
characteristics: u16,
}
const IMAGE_FILE_MACHINE_I386: u16 = 0x014C;
const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
const IMAGE_FILE_MACHINE_ARM: u16 = 0x01C4;
const IMAGE_FILE_MACHINE_ARM64: u16 = 0xAA64;
fn get_dll_path(dll_name: &str) -> Result<PathBuf, String> {
unsafe {
// 使用libloading加载DLL
// 转换DLL名称为C字符串
let dll_name_c =
CString::new(dll_name).map_err(|e| format!("Failed to convert to CString: {}", e))?;
// 获取DLL的模块句柄
let h_instance: HINSTANCE = GetModuleHandleA(dll_name_c.as_ptr() as *const c_char);
if h_instance.is_null() {
return Err("Failed to get module handle".to_string());
}
// 获取DLL文件路径
let mut buffer: [c_char; 260] = [0; 260];
let length = GetModuleFileNameA(h_instance, buffer.as_mut_ptr(), buffer.len() as u32);
if length == 0 {
return Err("Failed to get module file name".to_string());
}
let path = CStr::from_ptr(buffer.as_ptr());
let path_str = path
.to_str()
.map_err(|e| format!("Failed to convert to &str: {}", e))?;
Ok(PathBuf::from(path_str))
}
}
pub fn check_win_tun_dll() -> io::Result<()> {
let _lib = unsafe {
Library::new("wintun.dll").map_err(|_| {
io::Error::new(
io::ErrorKind::NotFound,
"wintun.dll not found,Please download https://www.wintun.net",
)
})
};
match get_dll_path("wintun.dll") {
Ok(path) => match_platform(path),
Err(e) => {
// 能加载说明存在wintun,这里获取不到路径是代码的问题
log::info!("{:?}", e);
Ok(())
}
}
}
fn match_platform(path: PathBuf) -> io::Result<()> {
let current_arch = if cfg!(target_arch = "x86") {
"x86"
} else if cfg!(target_arch = "x86_64") {
"AMD64"
} else if cfg!(target_arch = "arm") {
"ARM"
} else if cfg!(target_arch = "aarch64") {
"ARM64"
} else {
return Ok(());
};
let mut file = File::open(&path)?;
// 读取 DOS 头部
let mut dos_header = [0u8; std::mem::size_of::<DosHeader>()];
file.read_exact(&mut dos_header)?;
let dos_header: DosHeader = unsafe { std::ptr::read(dos_header.as_ptr() as *const _) };
if dos_header.e_magic != 0x5A4D {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Not a valid PE file {:?}", path),
));
}
// 跳转到 PE 头部
file.seek(io::SeekFrom::Start(dos_header.e_lfanew as u64))?;
// 读取 PE 头部
let mut pe_signature = [0u8; 4];
file.read_exact(&mut pe_signature)?;
if &pe_signature != b"PE\0\0" {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Not a valid PE file {:?}", path),
));
}
// 读取文件头部
let mut file_header = [0u8; std::mem::size_of::<FileHeader>()];
file.read_exact(&mut file_header)?;
let file_header: FileHeader = unsafe { std::ptr::read(file_header.as_ptr() as *const _) };
let dll_arch = match file_header.machine {
IMAGE_FILE_MACHINE_I386 => "x86",
IMAGE_FILE_MACHINE_AMD64 => "AMD64",
IMAGE_FILE_MACHINE_ARM => "ARM",
IMAGE_FILE_MACHINE_ARM64 => "ARM64",
_ => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Unknown machine type: {}", file_header.machine),
))
}
};
if dll_arch != current_arch {
return Err(io::Error::new(
io::ErrorKind::Other,
format!(
"wintun.dll architecture ({}) does not match the current platform architecture ({}).",
dll_arch, current_arch
),
));
}
Ok(())
}
+3
View File
@@ -16,6 +16,9 @@ impl Device {
Ok(Device::Tun(tun::Device::new(name)?))
}
}
pub fn check_tun_dll() -> io::Result<()> {
crate::windows::check::check_win_tun_dll()
}
}
impl IFace for Device {
+1
View File
@@ -3,6 +3,7 @@ use std::os::windows::process::CommandExt;
use winapi::shared::minwindef::DWORD;
use winapi::um::winbase::CREATE_NO_WINDOW;
mod check;
mod device;
mod ffi;
mod netsh;
+39 -20
View File
@@ -1,9 +1,8 @@
#![allow(dead_code)]
use libloading::Library;
use sha2::Digest;
use std::io;
use std::net::Ipv4Addr;
use rand::Rng;
use winapi::um::winbase;
use winapi::um::{synchapi, winnt};
@@ -78,9 +77,10 @@ impl Device {
));
}
wintun_log::set_default_logger_if_unset(&win_tun);
let _ = Self::delete_for_name(&win_tun, &name_utf16);
let mut guid_bytes: [u8; 16] = [0u8; 16];
rand::thread_rng().fill(&mut guid_bytes);
if Self::delete_for_name(&win_tun, &name_utf16).is_ok() {
std::thread::sleep(std::time::Duration::from_millis(500));
}
let guid_bytes: [u8; 16] = hash_guid(&name);
let guid = u128::from_ne_bytes(guid_bytes);
//SAFETY: guid is a unique integer so transmuting either all zeroes or the user's preferred
//guid to the winapi guid type is safe and will allow the windows kernel to see our GUID
@@ -101,7 +101,7 @@ impl Device {
));
}
// 开启session
let session = win_tun.WintunStartSession(adapter, 128 * 1024);
let session = win_tun.WintunStartSession(adapter, 4 * 1024 * 1024);
if session.is_null() {
log::error!("session.is_null {:?}", io::Error::last_os_error());
return Err(io::Error::new(
@@ -152,7 +152,15 @@ impl Device {
Ok(())
}
}
fn hash_guid(input: &str) -> [u8; 16] {
let mut hasher = sha2::Sha256::new();
hasher.update(input.as_bytes());
hasher.update(b"VNT");
hasher.update(input.as_bytes());
hasher.update(b"2024");
let hash: [u8; 32] = hasher.finalize().into();
hash[..16].try_into().unwrap()
}
impl IFace for Device {
fn version(&self) -> io::Result<String> {
let version = unsafe { self.win_tun.WintunGetRunningDriverVersion() };
@@ -172,7 +180,7 @@ impl IFace for Device {
fn shutdown(&self) -> io::Result<()> {
unsafe {
if 0 == synchapi::SetEvent(self.shutdown_event) {
if winapi::shared::minwindef::TRUE == synchapi::SetEvent(self.shutdown_event) {
Ok(())
} else {
Err(io::Error::last_os_error())
@@ -237,7 +245,10 @@ impl Device {
if last_error == winapi::shared::winerror::ERROR_NO_MORE_ITEMS {
Ok(None)
} else {
Err(io::Error::new(io::ErrorKind::Other, "try_receive failed"))
Err(io::Error::new(
io::ErrorKind::Other,
format!("try_receive failed {:?}", io::Error::last_os_error()),
))
}
} else {
Ok(Some(packet::TunPacket {
@@ -254,13 +265,21 @@ impl Device {
loop {
//Try 16 times to receive without blocking so we don't have to issue a syscall to wait
//for the event if packets are being received at a rapid rate
for _i in 0..20 {
match self.try_receive()? {
None => {
continue;
}
Some(packet) => {
return Ok(packet);
for i in 0..20 {
match self.try_receive() {
Ok(data) => match data {
None => {
continue;
}
Some(packet) => {
return Ok(packet);
}
},
Err(e) => {
if i > 10 {
// 某些系统存在错误退出的情况(原因不明),这里尝试忽略部分错误
return Err(e);
}
}
}
}
@@ -284,11 +303,11 @@ impl Device {
if result == winbase::WAIT_OBJECT_0 {
//We have data!
continue;
} else if result == winbase::WAIT_OBJECT_0 + 1 {
} else {
//Shutdown event triggered
return Err(io::Error::new(
io::ErrorKind::Other,
"Shutdown event triggered",
format!("Shutdown event triggered {}", io::Error::last_os_error()),
));
}
}
@@ -336,8 +355,8 @@ impl Drop for Device {
}
self.win_tun.WintunEndSession(self.session);
self.win_tun.WintunCloseAdapter(self.adapter);
if 0 != self.win_tun.WintunDeleteDriver() {
log::warn!("WintunDeleteDriver failed")
if winapi::shared::minwindef::FALSE == self.win_tun.WintunDeleteDriver() {
log::warn!("WintunDeleteDriver failed {:?}", io::Error::last_os_error())
}
}
}