Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a76280c53b | ||
|
|
90ff03e27c | ||
|
|
5eed05989f | ||
|
|
ac939746bd | ||
|
|
b7532e89c2 | ||
|
|
74f44d6961 | ||
|
|
86fc27c233 | ||
|
|
4b6bb0e5f7 | ||
|
|
215337fd8a | ||
|
|
e54341567a | ||
|
|
1ce3e9ff2e | ||
|
|
ffdb5ceb6b | ||
|
|
faa78445b1 | ||
|
|
440a832ace | ||
|
|
01cf8806e2 | ||
|
|
a85e0c6d06 | ||
|
|
fee3b24df4 | ||
|
|
d8a9ec5732 | ||
|
|
0e4294415e | ||
|
|
9df324f402 | ||
|
|
3b1236cfd0 | ||
|
|
699262d79e | ||
|
|
f6cfa1b84c | ||
|
|
1338bcbbc5 | ||
|
|
4215488cb6 | ||
|
|
ccd6e44c2b | ||
|
|
b12b0b95a0 | ||
|
|
948f3d5d24 | ||
|
|
cf4fc54dfd | ||
|
|
5a9e31bded | ||
|
|
b61c140c24 | ||
|
|
035ae46ee5 | ||
|
|
b57a38e81e | ||
|
|
be767ae300 | ||
|
|
607c8c2e9f | ||
|
|
d3dce7a3cc | ||
|
|
ff2bbdd837 | ||
|
|
b771b6c074 | ||
|
|
ff389647c0 | ||
|
|
49bec2d6aa | ||
|
|
ee359dc0d8 | ||
|
|
d4fc28dca3 | ||
|
|
1130f69a82 |
@@ -105,6 +105,8 @@ jobs:
|
||||
run: |
|
||||
# dependencies are only needed on ubuntu as that's the only place where
|
||||
# we make cross-compilation
|
||||
rustup set auto-self-update disable
|
||||
|
||||
if [[ $OS =~ ^ubuntu.*$ ]]; then
|
||||
sudo apt-get update && sudo apt-get install -qq crossbuild-essential-arm64 crossbuild-essential-armhf musl-tools
|
||||
# curl -s musl.cc | grep mipsel
|
||||
@@ -136,6 +138,9 @@ jobs:
|
||||
# mips平台使用1.71.1版本
|
||||
rustup install 1.71.1
|
||||
rustup default 1.71.1
|
||||
else
|
||||
rustup install 1.77
|
||||
rustup default 1.77
|
||||
fi
|
||||
|
||||
if [ -n "$MUSL_URI" ]; then
|
||||
@@ -144,8 +149,11 @@ jobs:
|
||||
tar zxf ./musl_gcc/$MUSL_URI.tgz -C ./musl_gcc/
|
||||
sudo ln -s $(pwd)/musl_gcc/$MUSL_URI/bin/*gcc /usr/bin/
|
||||
fi
|
||||
else
|
||||
rustup install 1.77
|
||||
rustup default 1.77
|
||||
fi
|
||||
|
||||
rustup -V
|
||||
|
||||
# some additional configuration for cross-compilation on linux
|
||||
cat >>~/.cargo/config <<EOF
|
||||
|
||||
Generated
+261
-4
@@ -2,6 +2,21 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
|
||||
[[package]]
|
||||
name = "addr2line"
|
||||
version = "0.21.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb"
|
||||
dependencies = [
|
||||
"gimli",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "adler"
|
||||
version = "1.0.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"
|
||||
|
||||
[[package]]
|
||||
name = "aead"
|
||||
version = "0.5.2"
|
||||
@@ -52,6 +67,24 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
|
||||
|
||||
[[package]]
|
||||
name = "android_log-sys"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ecc8056bf6ab9892dcd53216c83d1597487d7dacac16c8df6b877d127df9937"
|
||||
|
||||
[[package]]
|
||||
name = "android_logger"
|
||||
version = "0.13.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c494134f746c14dc653a35a4ea5aca24ac368529da5370ecf41fe0341c35772f"
|
||||
dependencies = [
|
||||
"android_log-sys",
|
||||
"env_logger",
|
||||
"log",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "android_system_properties"
|
||||
version = "0.1.5"
|
||||
@@ -79,6 +112,21 @@ version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f1fdabc7756949593fe60f30ec81974b613357de856987752631dea1e3394c80"
|
||||
|
||||
[[package]]
|
||||
name = "backtrace"
|
||||
version = "0.3.71"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d"
|
||||
dependencies = [
|
||||
"addr2line",
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"miniz_oxide",
|
||||
"object",
|
||||
"rustc-demangle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.6.0"
|
||||
@@ -147,6 +195,10 @@ name = "cc"
|
||||
version = "1.0.94"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "17f6e324229dc011159fcc089755d1e2e216a90d43a7dea6853ca740b84f35e7"
|
||||
dependencies = [
|
||||
"jobserver",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cesu8"
|
||||
@@ -160,6 +212,36 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "chacha20"
|
||||
version = "0.9.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chacha20poly1305"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
|
||||
dependencies = [
|
||||
"aead",
|
||||
"chacha20",
|
||||
"cipher",
|
||||
"poly1305",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "chrono"
|
||||
version = "0.4.38"
|
||||
@@ -182,6 +264,7 @@ checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -196,7 +279,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "common"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
|
||||
[[package]]
|
||||
name = "console"
|
||||
@@ -352,6 +435,16 @@ version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f"
|
||||
|
||||
[[package]]
|
||||
name = "env_logger"
|
||||
version = "0.10.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4cd405aab171cb85d6735e5c8d9db038c17d3ca007a4d2c25f337935c3d90580"
|
||||
dependencies = [
|
||||
"log",
|
||||
"regex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.1"
|
||||
@@ -422,6 +515,12 @@ dependencies = [
|
||||
"polyval",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gimli"
|
||||
version = "0.28.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253"
|
||||
|
||||
[[package]]
|
||||
name = "hashbrown"
|
||||
version = "0.12.3"
|
||||
@@ -434,6 +533,12 @@ version = "0.14.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.3.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024"
|
||||
|
||||
[[package]]
|
||||
name = "home"
|
||||
version = "0.5.9"
|
||||
@@ -536,6 +641,15 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d2b099aaa34a9751c5bf0878add70444e1ed2dd73f347be99003d4577277de6e"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.69"
|
||||
@@ -650,12 +764,27 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lz4_flex"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75761162ae2b0e580d7e7c390558127e5f01b4194debd6221fd8c207fc80e3f5"
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7"
|
||||
dependencies = [
|
||||
"adler",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "0.8.11"
|
||||
@@ -726,6 +855,25 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_cpus"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.32.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.19.0"
|
||||
@@ -817,6 +965,12 @@ dependencies = [
|
||||
"base64ct",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02"
|
||||
|
||||
[[package]]
|
||||
name = "pkcs1"
|
||||
version = "0.7.5"
|
||||
@@ -844,6 +998,17 @@ version = "0.3.30"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec"
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"
|
||||
dependencies = [
|
||||
"cpufeatures",
|
||||
"opaque-debug",
|
||||
"universal-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "polyval"
|
||||
version = "0.6.2"
|
||||
@@ -1096,6 +1261,12 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-demangle"
|
||||
version = "0.1.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
|
||||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.32"
|
||||
@@ -1195,6 +1366,25 @@ dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook"
|
||||
version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"signal-hook-registry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "2.2.0"
|
||||
@@ -1343,6 +1533,36 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.37.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787"
|
||||
dependencies = [
|
||||
"backtrace",
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"num_cpus",
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.60",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tun"
|
||||
version = "0.1.0"
|
||||
@@ -1437,13 +1657,16 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
|
||||
|
||||
[[package]]
|
||||
name = "vnt"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
"bytes",
|
||||
"cbc",
|
||||
"cfg_aliases",
|
||||
"chacha20",
|
||||
"chacha20poly1305",
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-queue",
|
||||
"crossbeam-utils",
|
||||
@@ -1453,6 +1676,7 @@ dependencies = [
|
||||
"libloading",
|
||||
"libsm",
|
||||
"log",
|
||||
"lz4_flex",
|
||||
"mio",
|
||||
"openssl-sys",
|
||||
"packet",
|
||||
@@ -1468,13 +1692,16 @@ dependencies = [
|
||||
"spki",
|
||||
"stun-format",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tun",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vnt-cli"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"chrono",
|
||||
"common",
|
||||
"console",
|
||||
@@ -1486,6 +1713,7 @@ dependencies = [
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_yaml",
|
||||
"signal-hook",
|
||||
"sudo",
|
||||
"uuid",
|
||||
"vnt",
|
||||
@@ -1494,8 +1722,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "vnt-jni"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
dependencies = [
|
||||
"android_logger",
|
||||
"common",
|
||||
"jni",
|
||||
"log",
|
||||
@@ -1851,3 +2080,31 @@ name = "zeroize"
|
||||
version = "1.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d"
|
||||
|
||||
[[package]]
|
||||
name = "zstd"
|
||||
version = "0.13.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d789b1514203a1120ad2429eae43a7bd32b90976a7bb8a05f7ec02fa88cc23a"
|
||||
dependencies = [
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-safe"
|
||||
version = "7.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1cd99b45c6bc03a018c8b8a86025678c87e55526064e38f9df301989dce7ec0a"
|
||||
dependencies = [
|
||||
"zstd-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-sys"
|
||||
version = "2.0.10+zstd.1.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c253a4914af5bafc8fa8c86ee400827e83cf6ec01195ec1f1ed8441bf00d65aa"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
@@ -39,7 +39,7 @@ A virtual network tool (VPN)
|
||||
```
|
||||
4. 最后可以用虚拟ip实现设备间相互访问
|
||||
|
||||
<img width="506" alt="ssh" src="https://raw.githubusercontent.com/lbl8603/vnt/dev/documents/img/ssh.jpg">
|
||||
<img width="506" alt="ssh" src="https://raw.githubusercontent.com/lbl8603/vnt/main/documents/img/ssh.jpg">
|
||||
5. 帮助,使用-h命令查看
|
||||
|
||||
### 更多玩法
|
||||
@@ -73,35 +73,48 @@ cargo build -p vnt-cli --no-default-features
|
||||
|
||||
features说明
|
||||
|
||||
| feature | 说明 | 是否默认 |
|
||||
|------------------|----------------------|------|
|
||||
| openssl | 使用openssl中的aes_ecb算法 | 否 |
|
||||
| openssl-vendored | 从源码编译openssl | 否 |
|
||||
| ring-cipher | 使用ring中的aes_gcm算法 | 否 |
|
||||
| aes_cbc | 支持aes_cbc加密 | 是 |
|
||||
| aes_ecb | 支持aes_ecb加密 | 是 |
|
||||
| aes_gcm | 支持aes_gcm加密 | 是 |
|
||||
| sm4_cbc | 支持sm4_cbc加密 | 是 |
|
||||
| server_encrypt | 支持服务端加密 | 是 |
|
||||
| ip_proxy | 内置ip代理 | 是 |
|
||||
| feature | 说明 | 是否默认 |
|
||||
|-------------------|--------------------------------|------|
|
||||
| openssl | 使用openssl中的加密算法 | 否 |
|
||||
| openssl-vendored | 从源码编译openssl | 否 |
|
||||
| ring-cipher | 使用ring中的加密算法 | 否 |
|
||||
| aes_cbc | 支持aes_cbc加密 | 是 |
|
||||
| aes_ecb | 支持aes_ecb加密 | 是 |
|
||||
| aes_gcm | 支持aes_gcm加密 | 是 |
|
||||
| sm4_cbc | 支持sm4_cbc加密 | 是 |
|
||||
| chacha20_poly1305 | 支持chacha20和chacha20_poly1305加密 | 是 |
|
||||
| server_encrypt | 支持服务端加密 | 是 |
|
||||
| ip_proxy | 内置ip代理 | 是 |
|
||||
| port_mapping | 端口映射 | 是 |
|
||||
| log | 日志 | 是 |
|
||||
| command | list、route等命令 | 是 |
|
||||
| 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
|
||||
@@ -144,6 +157,7 @@ sudo iptables-restore iptables.rules
|
||||
```
|
||||
|
||||
### macos
|
||||
|
||||
```shell
|
||||
# 开启ip转发
|
||||
sudo sysctl -w net.ipv4.ip_forward=1
|
||||
@@ -153,6 +167,7 @@ nat on en0 from 10.26.0.0/24 to any -> (en0)
|
||||
# 加载规则
|
||||
sudo pfctl -f /etc/pf.conf -e
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### 支持平台
|
||||
@@ -255,10 +270,15 @@ vnt默认使用10.26.0.0/24网段,和本地网络适配器的ip冲突
|
||||
2. 如果p2p后效果很差,可以选择禁用p2p(vnt-cli增加--use-channel relay 参数)
|
||||
|
||||
#### 问题4:重启后虚拟IP发生变化,或指定了IP不能启动
|
||||
|
||||
##### 可能原因:
|
||||
|
||||
设备重启后程序自动获取的id值改变,导致注册时重新分配了新的IP,或是IP冲突
|
||||
|
||||
##### 解决方法:
|
||||
|
||||
1. 命令行启动增加-d参数(使用配置文件启动则在配置文件中增加device_id参数),要保证每个设备的值都不一样,取值可以任意64位以内字符串
|
||||
|
||||
</details>
|
||||
|
||||
### 交流群
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "common"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
@@ -7,33 +7,33 @@ pub fn ips_parse(ips: &Vec<String>) -> Result<Vec<(u32, u32, Ipv4Addr)>, String>
|
||||
let net = if let Some(net) = split.next() {
|
||||
net
|
||||
} else {
|
||||
return Err("ipv4/mask,ipv4".to_string());
|
||||
return Err(format!("ipv4/mask,ipv4 {:?}", x));
|
||||
};
|
||||
let ip = if let Some(ip) = split.next() {
|
||||
ip
|
||||
} else {
|
||||
return Err("ipv4/mask,ipv4".to_string());
|
||||
return Err(format!("ipv4/mask,ipv4 {:?}", x));
|
||||
};
|
||||
let ip = if let Ok(ip) = ip.parse::<Ipv4Addr>() {
|
||||
ip
|
||||
} else {
|
||||
return Err("not ipv4".to_string());
|
||||
return Err(format!("not ipv4 {:?}", ip));
|
||||
};
|
||||
let mut split = net.split("/");
|
||||
let dest = if let Some(dest) = split.next() {
|
||||
dest
|
||||
} else {
|
||||
return Err("no ipv4/mask".to_string());
|
||||
return Err(format!("no ipv4/mask {:?}", net));
|
||||
};
|
||||
let mask = if let Some(mask) = split.next() {
|
||||
mask
|
||||
} else {
|
||||
return Err("no netmask".to_string());
|
||||
return Err(format!("no netmask {:?}", net));
|
||||
};
|
||||
let dest = if let Ok(dest) = dest.parse::<Ipv4Addr>() {
|
||||
dest
|
||||
} else {
|
||||
return Err("not ipv4".to_string());
|
||||
return Err(format!("not ipv4 {:?}", dest));
|
||||
};
|
||||
let mask = to_ip(mask)?;
|
||||
in_ips_c.push((u32::from_be_bytes(dest.octets()), mask, ip));
|
||||
@@ -48,17 +48,17 @@ pub fn out_ips_parse(ips: &Vec<String>) -> Result<Vec<(u32, u32)>, String> {
|
||||
let dest = if let Some(dest) = split.next() {
|
||||
dest
|
||||
} else {
|
||||
return Err("no ipv4/mask".to_string());
|
||||
return Err(format!("no ipv4/mask {:?}", x));
|
||||
};
|
||||
let mask = if let Some(mask) = split.next() {
|
||||
mask
|
||||
} else {
|
||||
return Err("no netmask".to_string());
|
||||
return Err(format!("no netmask {:?}", x));
|
||||
};
|
||||
let dest = if let Ok(dest) = dest.parse::<Ipv4Addr>() {
|
||||
dest
|
||||
} else {
|
||||
return Err("not ipv4".to_string());
|
||||
return Err(format!("not ipv4 {:?}", dest));
|
||||
};
|
||||
let mask = to_ip(mask)?;
|
||||
in_ips_c.push((u32::from_be_bytes(dest.octets()), mask));
|
||||
|
||||
@@ -55,7 +55,10 @@ pub fn get_unique_identifier() -> Option<String> {
|
||||
// 对 linux 或 wsl 来说,读取 /etc/machine-id 即可获取当前操作系统的
|
||||
// 唯一标识,而且某些环境没有预装`dmidecode`命令
|
||||
if let Ok(identifier) = std::fs::read_to_string("/etc/machine-id") {
|
||||
return Some(identifier);
|
||||
let identifier = identifier.trim();
|
||||
if !identifier.is_empty() {
|
||||
return Some(identifier.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let output = match Command::new("dmidecode")
|
||||
@@ -70,7 +73,7 @@ pub fn get_unique_identifier() -> Option<String> {
|
||||
};
|
||||
|
||||
let result = String::from_utf8_lossy(&output.stdout);
|
||||
let identifier = result.trim().to_string();
|
||||
let identifier = result.trim();
|
||||
if identifier.is_empty() {
|
||||
None
|
||||
} else {
|
||||
|
||||
+19
-10
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "vnt-cli"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
vnt = { path = "../vnt", package = "vnt",default-features = false }
|
||||
vnt = { path = "../vnt", package = "vnt", default-features = false }
|
||||
common = { path = "../common" }
|
||||
getopts = "0.2.21"
|
||||
console = "0.15.2"
|
||||
@@ -14,7 +14,8 @@ os_info = "3.7.0"
|
||||
serde = "1.0"
|
||||
serde_yaml = "0.9.32"
|
||||
log = "0.4.17"
|
||||
log4rs = "1.2.0"
|
||||
log4rs = { version = "1.2.0", optional = true }
|
||||
anyhow = "1.0.82"
|
||||
[dependencies.uuid]
|
||||
version = "1.4.1"
|
||||
features = [
|
||||
@@ -23,21 +24,29 @@ features = [
|
||||
|
||||
[target.'cfg(any(target_os = "linux",target_os = "macos"))'.dependencies]
|
||||
sudo = "0.6.0"
|
||||
signal-hook = "0.3.17"
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
winapi = { version = "0.3.9", features = ["handleapi", "processthreadsapi", "winnt", "securitybaseapi", "impl-default"] }
|
||||
|
||||
[features]
|
||||
default = ["server_encrypt","aes_gcm","aes_cbc","aes_ecb","sm4_cbc","ip_proxy"]
|
||||
default = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "ip_proxy", "port_mapping", "log", "command", "file_config", "lz4"]
|
||||
openssl = ["vnt/openssl"]
|
||||
openssl-vendored = ["vnt/openssl-vendored"]
|
||||
ring-cipher = ["vnt/ring-cipher"]
|
||||
aes_cbc=["vnt/aes_cbc"]
|
||||
aes_ecb=["vnt/aes_ecb"]
|
||||
sm4_cbc=["vnt/sm4_cbc"]
|
||||
aes_gcm=["vnt/aes_gcm"]
|
||||
server_encrypt=["vnt/server_encrypt"]
|
||||
ip_proxy=["vnt/ip_proxy"]
|
||||
aes_cbc = ["vnt/aes_cbc"]
|
||||
aes_ecb = ["vnt/aes_ecb"]
|
||||
sm4_cbc = ["vnt/sm4_cbc"]
|
||||
aes_gcm = ["vnt/aes_gcm"]
|
||||
chacha20_poly1305 = ["vnt/chacha20_poly1305"]
|
||||
server_encrypt = ["vnt/server_encrypt"]
|
||||
ip_proxy = ["vnt/ip_proxy"]
|
||||
port_mapping = ["vnt/port_mapping"]
|
||||
lz4 = ["vnt/lz4_compress"]
|
||||
zstd = ["vnt/zstd_compress"]
|
||||
log = ["log4rs"]
|
||||
command = []
|
||||
file_config = []
|
||||
[build-dependencies]
|
||||
embed-manifest = "1.4.0"
|
||||
rand = "0.8.5"
|
||||
|
||||
+118
-24
@@ -1,31 +1,54 @@
|
||||
## 模块介绍
|
||||
|
||||
体积小,可以在服务器、路由器等环境使用
|
||||
|
||||
## 详细参数说明
|
||||
|
||||
### -k `<token>`
|
||||
|
||||
一个虚拟局域网的标识,在同一服务器下,相同token的设备会组建一个局域网
|
||||
|
||||
### -n `<name>`
|
||||
|
||||
设备名称,方便区分不同设备
|
||||
|
||||
### -d `<id>`
|
||||
|
||||
设备id,每台设备的唯一标识,注意不要重复
|
||||
|
||||
### -c
|
||||
|
||||
关闭控制台交互式命令,后台运行时可以加此参数
|
||||
|
||||
### -s `<server>`
|
||||
注册和中继服务器地址,注册和转发数据
|
||||
|
||||
注册和中继服务器地址,注册和转发数据,以'TXT:'开头表示解析TXT记录,TXT记录内容必须是'host:port'形式的服务器地址
|
||||
|
||||
### -e `<stun-server>`
|
||||
|
||||
使用stun服务探测客户端NAT类型,不同类型有不同的打洞策略
|
||||
|
||||
### -a
|
||||
|
||||
加了此参数表示使用tap网卡,默认使用tun网卡,tun网卡效率更高
|
||||
|
||||
注意:仅在windows上支持使用tap,用于兼容低版本windows系统(低版本windows不支持wintun)
|
||||
|
||||
### --nic `<tun0>`
|
||||
|
||||
指定虚拟网卡名称,默认tun模式使用vnt-tun,tap模式使用vnt-tap
|
||||
|
||||
### -i `<in-ip>`、-o `<out-ip>`
|
||||
|
||||
配置点对网(IP代理)时使用,例如A(虚拟ip:10.26.0.2)通过B(虚拟ip:10.26.0.3,本地出口ip:192.168.0.10)访问C(目标网段192.168.0.0/24),
|
||||
配置点对网(IP代理)时使用,例如A(虚拟ip:10.26.0.2)通过B(虚拟ip:10.26.0.3,本地出口ip:192.168.0.10)访问C(
|
||||
目标网段192.168.0.0/24),
|
||||
|
||||
则在A配置 **'-i 192.168.0.0/24,10.26.0.3'** ,表示将192.168.0.0/24网段的数据都转发到10.26.0.3节点
|
||||
|
||||
在B配置 **'-o 192.168.0.0/24'** ,表示允许将数据转发到 192.168.0.0/24 ,允许转发所有网段可以使用 **'-o 0.0.0.0/0'**
|
||||
|
||||
-i和-o参数均可使用多次,来指定不同网段,例如 **'-o 192.168.1.0/24 -o 192.168.2.0/24'** 表示允许转发目标为192.168.1.0/24或192.168.2.0/24这两个网段的数据
|
||||
-i和-o参数均可使用多次,来指定不同网段,例如 **'-o 192.168.1.0/24 -o 192.168.2.0/24'**
|
||||
表示允许转发目标为192.168.1.0/24或192.168.2.0/24这两个网段的数据
|
||||
|
||||
### -w `<password>`
|
||||
|
||||
@@ -37,9 +60,11 @@
|
||||
| 大于等于8 | AES256-GCM |
|
||||
|
||||
### -W
|
||||
|
||||
开启和服务端通信的数据加密,采用rsa+aes256gcm加密客户端和服务端之间通信的数据,可以避免token泄漏、中间人攻击
|
||||
|
||||
注意:
|
||||
|
||||
1. -w `<password>`是用于客户端-客户端之间的加密,password不会传递到服务端,只添加这个参数不会加密客户端-服务端通信的数据
|
||||
2. -W 用于开启客户端-服务端之间的加密
|
||||
|
||||
@@ -47,55 +72,101 @@
|
||||
|
||||
设置虚拟网卡的mtu值,大多数情况下使用默认值效率会更高,也可根据实际情况微调这个值,不加密默认为1450,加密默认为1410
|
||||
|
||||
### --tcp
|
||||
### --tcp
|
||||
|
||||
和服务端使用tcp通信。有些网络提供商对UDP限制比较大,这个时候可以选择使用TCP模式,提高稳定性。一般来说udp延迟和消耗更低
|
||||
|
||||
### --ip `<IP>`
|
||||
|
||||
指定虚拟ip,指定的ip不能和其他设备重复,必须有效并且在服务端所属网段下,默认情况由服务端分配
|
||||
|
||||
### --par `<parallel>`
|
||||
|
||||
任务并行度(必须为正整数),默认值为1,该值表示处理网卡读写的任务数,组网设备数较多、处理延迟较大时可适当调大此值
|
||||
|
||||
### --model `<model>`
|
||||
加密模式,可选值 aes_gcm/aes_cbc/aes_ecb/sm4_cbc,默认使用aes_gcm,通常情况aes_gcm安全性高、aes_ecb性能更好,但是在低性能设备上sm4_cbc也许速度会更快;
|
||||
|
||||
加密模式,可选值
|
||||
aes_gcm/aes_cbc/aes_ecb/sm4_cbc/chacha20_poly1305/chacha20/xor,默认使用aes_gcm,通常情况aes_gcm和chacha20_poly1305安全性高。
|
||||
各种加密模式的安全性和速度都不相同,请按需选取
|
||||
|
||||
| 密码位数 | model | 加密算法 |
|
||||
|-------|---------|------------|
|
||||
| 1~8位 | aes_gcm | AES128-GCM |
|
||||
| `>=`8 | aes_gcm | AES256-GCM |
|
||||
| 1~8位 | aes_cbc | AES128-CBC |
|
||||
| `>=`8 | aes_cbc | AES256-CBC |
|
||||
| 1~8位 | aes_ecb | AES128-ECB |
|
||||
| `>=`8 | aes_ecb | AES256-ECB |
|
||||
| `>0` | sm4_cbc | SM4-CBC |
|
||||
### --finger
|
||||
特别说明:xor只是对数据进行简单异或,仅仅避免了明文传输,安全性很差,同时对性能影响也极小;
|
||||
|
||||
| 密码位数 | model | 加密算法 |
|
||||
|-------|-------------------|-------------------|
|
||||
| 1~8位 | aes_gcm | AES128-GCM |
|
||||
| `>=`8 | aes_gcm | AES256-GCM |
|
||||
| 1~8位 | aes_cbc | AES128-CBC |
|
||||
| `>=`8 | aes_cbc | AES256-CBC |
|
||||
| 1~8位 | aes_ecb | AES128-ECB |
|
||||
| `>=`8 | aes_ecb | AES256-ECB |
|
||||
| `>0` | sm4_cbc | SM4-CBC |
|
||||
| `>0` | chacha20_poly1305 | ChaCha20-Poly1305 |
|
||||
| `>0` | chacha20 | ChaCha20 |
|
||||
| `>0` | xor | 简单异或混淆 |
|
||||
|
||||
### --finger
|
||||
|
||||
开启数据指纹校验,可增加安全性,如果服务端开启指纹校验,则客户端也必须开启,开启会损耗一部分性能
|
||||
|
||||
注意:默认情况下服务端不会对中转的数据做校验,如果要对中转的数据做校验,则需要客户端、服务端都开启此参数
|
||||
|
||||
### --punch `<punch>`
|
||||
取值ipv4/ipv6,选择只使用ipv4打洞或者只使用ipv6打洞,默认两则都会使用
|
||||
|
||||
取值ipv4/ipv6,选择只使用ipv4打洞或者只使用ipv6打洞,默认两者都会使用
|
||||
|
||||
### --ports `<port1,port2>`
|
||||
指定本地监听的端口组,多个端口使用逗号分隔,多个端口可以分摊流量,增加并发,tcp会监听端口组的第一个端口,用于tcp直连
|
||||
|
||||
指定本地监听的端口组,多个端口使用逗号分隔,多个端口可以分摊流量,增加并发、减缓流量限制,tcp会监听端口组的第一个端口,用于tcp直连
|
||||
|
||||
- 例1:‘--ports 12345,12346,12347’ 表示udp监听12345、12346、12347这三个端口,tcp监听12345端口
|
||||
- 例2:‘--ports 0,0’ 表示udp监听两个未使用的端口,tcp监听一个未使用的端口
|
||||
|
||||
### --cmd
|
||||
|
||||
开启交互式命令,开启后可以直接在窗口下输入命令,如需后台运行请勿开启
|
||||
|
||||
### --first_latency
|
||||
|
||||
优先使用低延迟通道,默认情况下优先使用p2p通道,某些情况下可能p2p比客户端中继延迟更高,可使用此参数进行优化传输
|
||||
|
||||
### --no-proxy
|
||||
|
||||
关闭内置的ip代理,内置的代理较为简单,而且一般来说直接使用网卡NAT转发性能会更高,
|
||||
有需要可以自行配置NAT转发,[可参考‘编译’小节中的NAT配置](https://github.com/lbl8603/vnt#%E7%BC%96%E8%AF%91)
|
||||
|
||||
### --dns `<223.5.5.5>`
|
||||
|
||||
设置域名解析服务器地址,可以设置多个。如果使用TXT记录的域名,则dns默认使用223.5.5.5和114.114.114.114,端口省略值为53
|
||||
|
||||
当地址解析失败时,会依次尝试后面的dns,直到有A记录、AAAA记录(或TXT记录)的解析结果
|
||||
|
||||
### --mapping `<udp:0.0.0.0:80->10.26.0.10:80>`
|
||||
|
||||
端口映射,可以设置多个映射地址,例如 '--mapping udp:0.0.0.0:80->10.26.0.10:80 --mapping tcp:0.0.0.0:80->10.26.0.11:81'
|
||||
表示将本地udp 80端口的数据转发到10.26.0.10:80,将本地tcp 80端口的数据转发到10.26.0.11:81,转发的目的地址可以使用域名+端口
|
||||
|
||||
### --compressor `<lz4>`
|
||||
|
||||
启用压缩,默认仅支持lz4压缩,开启压缩后,如果数据包长度大于等于128,则会使用压缩,否则还是会按原数据发送
|
||||
|
||||
也支持开启zstd压缩,但是需要自行编译,编译时加入参数--features zstd
|
||||
|
||||
如果宽度速度比较慢,可以考虑使用高级别的压缩
|
||||
|
||||
### -f `<conf>`
|
||||
|
||||
指定配置文件
|
||||
配置文件采用yaml格式,可参考:
|
||||
|
||||
```yaml
|
||||
# 全部参数
|
||||
tap: false #是否使用tap
|
||||
tap: false #是否使用tap 仅在windows上支持使用tap
|
||||
token: xxx #组网token
|
||||
device_id: xxx #当前设备id
|
||||
name: windows 11 #当前设备名称
|
||||
server_address: ip:port #注册和中继服务器
|
||||
stun_server: #stun服务器
|
||||
stun_server: #stun服务器
|
||||
- stun1.l.google.com:19302
|
||||
- stun2.l.google.com:19302
|
||||
in_ips: #代理ip入站
|
||||
@@ -111,8 +182,8 @@ server_encrypt: true #服务端加密
|
||||
parallel: 1 #任务并行度
|
||||
cipher_model: aes_gcm #客户端加密算法
|
||||
finger: false #关闭数据指纹
|
||||
punch_model: ipv4 #打洞模式
|
||||
ports:
|
||||
punch_model: ipv4 #打洞模式,表示只使用ipv4地址打洞,默认会同时使用v6和v4
|
||||
ports:
|
||||
- 0 #使用随机端口,tcp监听此端口
|
||||
- 0
|
||||
cmd: false #关闭控制台输入
|
||||
@@ -122,27 +193,50 @@ device_name: vnt-tun #网卡名称
|
||||
packet_loss: 0 #指定丢包率 取值0~1之间的数 用于模拟弱网
|
||||
packet_delay: 0 #指定延迟 单位毫秒 用于模拟弱网
|
||||
dns:
|
||||
- 8.8.8.8:53
|
||||
- 223.5.5.5 # 首选dns
|
||||
- 8.8.8.8 # 备选dns
|
||||
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数据
|
||||
```
|
||||
|
||||
或者需要哪个配置就加哪个,当然token是必须的
|
||||
|
||||
```yaml
|
||||
# 部分参数
|
||||
token: xxx #组网token
|
||||
```
|
||||
|
||||
### --use-channel `<relay/p2p>`
|
||||
|
||||
- relay:仅中继模式,会禁止打洞/p2p直连,只使用服务器转发
|
||||
- p2p:仅直连模式,会禁止网络数据从服务器/客户端转发,只会使用服务器转发控制包
|
||||
|
||||
### --packet-loss `<0>`
|
||||
模拟丢包,取值0~1之间的小数,程序会按设定的概率主动丢包。在模拟弱网环境会有帮助。
|
||||
|
||||
模拟丢包,取值0~1之间的小数,程序会按设定的概率主动丢包。在模拟弱网环境时会有帮助。
|
||||
|
||||
### --packet-delay `<0>`
|
||||
|
||||
模拟延迟,整数,单位毫秒(ms),程序会按设定的值延迟发包,可用于模拟弱网
|
||||
|
||||
### --list
|
||||
|
||||
在后台运行时,查看其他设备列表
|
||||
|
||||
### --all
|
||||
|
||||
在后台运行时,查看其他设备完整信息
|
||||
|
||||
### --info
|
||||
|
||||
在后台运行时,查看当前设备信息
|
||||
### --route
|
||||
|
||||
### --route
|
||||
|
||||
在后台运行时,查看数据转发路径
|
||||
|
||||
### --stop
|
||||
|
||||
停止后台运行
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct Info {
|
||||
pub name: String,
|
||||
@@ -13,6 +14,9 @@ pub struct Info {
|
||||
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)>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
|
||||
@@ -185,6 +185,12 @@ pub fn command_info(vnt: &Vnt) -> Info {
|
||||
.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();
|
||||
Info {
|
||||
name,
|
||||
virtual_ip,
|
||||
@@ -198,5 +204,8 @@ pub fn command_info(vnt: &Vnt) -> Info {
|
||||
ipv6_addr,
|
||||
up,
|
||||
down,
|
||||
port_mapping_list,
|
||||
in_ips,
|
||||
out_ips,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
use anyhow::anyhow;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::str::FromStr;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::get_device_id;
|
||||
use vnt::channel::punch::PunchModel;
|
||||
use vnt::channel::UseChannelType;
|
||||
use vnt::cipher::CipherModel;
|
||||
use vnt::compression::Compressor;
|
||||
use vnt::core::Config;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(default)]
|
||||
pub struct FileConfig {
|
||||
#[cfg(target_os = "windows")]
|
||||
pub tap: bool,
|
||||
pub token: String,
|
||||
pub device_id: String,
|
||||
pub name: String,
|
||||
pub server_address: String,
|
||||
pub stun_server: Vec<String>,
|
||||
pub dns: Vec<String>,
|
||||
pub in_ips: Vec<String>,
|
||||
pub out_ips: Vec<String>,
|
||||
pub password: Option<String>,
|
||||
pub mtu: Option<u32>,
|
||||
pub tcp: bool,
|
||||
pub ip: Option<String>,
|
||||
pub use_channel: String,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
pub no_proxy: bool,
|
||||
pub server_encrypt: bool,
|
||||
pub parallel: usize,
|
||||
pub cipher_model: Option<String>,
|
||||
pub finger: bool,
|
||||
pub punch_model: String,
|
||||
pub ports: Option<Vec<u16>>,
|
||||
pub cmd: bool,
|
||||
pub first_latency: bool,
|
||||
pub device_name: Option<String>,
|
||||
pub packet_loss: Option<f64>,
|
||||
pub packet_delay: u32,
|
||||
#[cfg(feature = "port_mapping")]
|
||||
pub mapping: Vec<String>,
|
||||
pub compressor: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for FileConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
#[cfg(target_os = "windows")]
|
||||
tap: false,
|
||||
token: "".to_string(),
|
||||
device_id: get_device_id(),
|
||||
name: os_info::get().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(),
|
||||
],
|
||||
dns: vec![],
|
||||
in_ips: vec![],
|
||||
out_ips: vec![],
|
||||
password: None,
|
||||
mtu: None,
|
||||
tcp: false,
|
||||
ip: None,
|
||||
use_channel: "all".to_string(),
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
no_proxy: false,
|
||||
server_encrypt: false,
|
||||
parallel: 1,
|
||||
cipher_model: None,
|
||||
finger: false,
|
||||
punch_model: "all".to_string(),
|
||||
ports: None,
|
||||
cmd: false,
|
||||
first_latency: false,
|
||||
device_name: None,
|
||||
packet_loss: None,
|
||||
packet_delay: 0,
|
||||
#[cfg(feature = "port_mapping")]
|
||||
mapping: vec![],
|
||||
compressor: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_config(file_path: &str) -> anyhow::Result<(Config, bool)> {
|
||||
let conf = std::fs::read_to_string(file_path)?;
|
||||
let file_conf = match serde_yaml::from_str::<FileConfig>(&conf) {
|
||||
Ok(val) => val,
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
return Err(anyhow!("{}", e));
|
||||
}
|
||||
};
|
||||
if file_conf.token.is_empty() {
|
||||
return Err(anyhow!("token is_empty"));
|
||||
}
|
||||
|
||||
let in_ips = match common::args_parse::ips_parse(&file_conf.in_ips) {
|
||||
Ok(in_ips) => in_ips,
|
||||
Err(e) => {
|
||||
return Err(anyhow!("in_ips {:?} error:{}", &file_conf.in_ips, e));
|
||||
}
|
||||
};
|
||||
let out_ips = match common::args_parse::out_ips_parse(&file_conf.out_ips) {
|
||||
Ok(out_ips) => out_ips,
|
||||
Err(e) => {
|
||||
return Err(anyhow!("out_ips {:?} error:{}", &file_conf.out_ips, e));
|
||||
}
|
||||
};
|
||||
let virtual_ip = match file_conf.ip.clone().map(|v| Ipv4Addr::from_str(&v)) {
|
||||
None => None,
|
||||
Some(r) => Some(r.map_err(|e| anyhow!("ip {:?} error:{}", &file_conf.ip, e))?),
|
||||
};
|
||||
let cipher_model = {
|
||||
#[cfg(not(any(feature = "aes_gcm", feature = "server_encrypt")))]
|
||||
if file_conf.password.is_some() && file_conf.cipher_model.is_none() {
|
||||
Err(anyhow!("cipher_model undefined"))?
|
||||
}
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
CipherModel::AesGcm
|
||||
};
|
||||
|
||||
let punch_model = PunchModel::from_str(&file_conf.punch_model).map_err(|e| anyhow!("{}", e))?;
|
||||
let use_channel_type =
|
||||
UseChannelType::from_str(&file_conf.use_channel).map_err(|e| anyhow!("{}", e))?;
|
||||
let compressor = if let Some(compressor) = file_conf.compressor.as_ref() {
|
||||
Compressor::from_str(compressor).map_err(|e| anyhow!("{}", e))?
|
||||
} else {
|
||||
Compressor::None
|
||||
};
|
||||
let config = Config::new(
|
||||
#[cfg(target_os = "windows")]
|
||||
file_conf.tap,
|
||||
file_conf.token,
|
||||
file_conf.device_id,
|
||||
file_conf.name,
|
||||
file_conf.server_address,
|
||||
file_conf.dns,
|
||||
file_conf.stun_server,
|
||||
in_ips,
|
||||
out_ips,
|
||||
file_conf.password,
|
||||
file_conf.mtu,
|
||||
file_conf.tcp,
|
||||
virtual_ip,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
file_conf.no_proxy,
|
||||
file_conf.server_encrypt,
|
||||
file_conf.parallel,
|
||||
cipher_model,
|
||||
file_conf.finger,
|
||||
punch_model,
|
||||
file_conf.ports,
|
||||
file_conf.first_latency,
|
||||
file_conf.device_name,
|
||||
use_channel_type,
|
||||
file_conf.packet_loss,
|
||||
file_conf.packet_delay,
|
||||
#[cfg(feature = "port_mapping")]
|
||||
file_conf.mapping,
|
||||
compressor,
|
||||
)?;
|
||||
Ok((config, file_conf.cmd))
|
||||
}
|
||||
+7
-160
@@ -1,165 +1,12 @@
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::str::FromStr;
|
||||
#[cfg(feature = "file_config")]
|
||||
mod file_config;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[cfg(feature = "file_config")]
|
||||
pub use file_config::read_config;
|
||||
|
||||
use vnt::channel::punch::PunchModel;
|
||||
use vnt::channel::UseChannelType;
|
||||
use vnt::cipher::CipherModel;
|
||||
use vnt::core::Config;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
#[serde(default)]
|
||||
pub struct FileConfig {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
pub tap: bool,
|
||||
pub token: String,
|
||||
pub device_id: String,
|
||||
pub name: String,
|
||||
pub server_address: String,
|
||||
pub stun_server: Vec<String>,
|
||||
pub dns: Vec<String>,
|
||||
pub in_ips: Vec<String>,
|
||||
pub out_ips: Vec<String>,
|
||||
pub password: Option<String>,
|
||||
pub mtu: Option<u32>,
|
||||
pub tcp: bool,
|
||||
pub ip: Option<String>,
|
||||
pub use_channel: String,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
pub no_proxy: bool,
|
||||
pub server_encrypt: bool,
|
||||
pub parallel: usize,
|
||||
pub cipher_model: String,
|
||||
pub finger: bool,
|
||||
pub punch_model: String,
|
||||
pub ports: Option<Vec<u16>>,
|
||||
pub cmd: bool,
|
||||
pub first_latency: bool,
|
||||
pub device_name: Option<String>,
|
||||
pub packet_loss: Option<f64>,
|
||||
pub packet_delay: u32,
|
||||
}
|
||||
|
||||
impl Default for FileConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
tap: false,
|
||||
token: "".to_string(),
|
||||
device_id: get_device_id(),
|
||||
name: os_info::get().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.qq.com:3478".to_string(),
|
||||
],
|
||||
dns: vec![],
|
||||
in_ips: vec![],
|
||||
out_ips: vec![],
|
||||
password: None,
|
||||
mtu: None,
|
||||
tcp: false,
|
||||
ip: None,
|
||||
use_channel: "all".to_string(),
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
no_proxy: false,
|
||||
server_encrypt: false,
|
||||
parallel: 1,
|
||||
cipher_model: "aes_gcm".to_string(),
|
||||
finger: false,
|
||||
punch_model: "all".to_string(),
|
||||
ports: None,
|
||||
cmd: false,
|
||||
first_latency: false,
|
||||
device_name: None,
|
||||
packet_loss: None,
|
||||
packet_delay: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read_config(file_path: &str) -> io::Result<(Config, bool)> {
|
||||
let conf = std::fs::read_to_string(file_path)?;
|
||||
let file_conf = match serde_yaml::from_str::<FileConfig>(&conf) {
|
||||
Ok(val) => val,
|
||||
Err(e) => {
|
||||
log::error!("{:?}", e);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, format!("{}", e)));
|
||||
}
|
||||
};
|
||||
if file_conf.token.is_empty() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "token is_empty"));
|
||||
}
|
||||
|
||||
let in_ips = match common::args_parse::ips_parse(&file_conf.in_ips) {
|
||||
Ok(in_ips) => in_ips,
|
||||
Err(e) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("in_ips {:?} error:{}", &file_conf.in_ips, e),
|
||||
));
|
||||
}
|
||||
};
|
||||
let out_ips = match common::args_parse::out_ips_parse(&file_conf.out_ips) {
|
||||
Ok(out_ips) => out_ips,
|
||||
Err(e) => {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("out_ips {:?} error:{}", &file_conf.out_ips, e),
|
||||
));
|
||||
}
|
||||
};
|
||||
let virtual_ip = match file_conf.ip.clone().map(|v| Ipv4Addr::from_str(&v)) {
|
||||
None => None,
|
||||
Some(r) => Some(r.map_err(|e| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("ip {:?} error:{}", &file_conf.ip, e),
|
||||
)
|
||||
})?),
|
||||
};
|
||||
|
||||
let cipher_model = CipherModel::from_str(&file_conf.cipher_model)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
|
||||
let punch_model = PunchModel::from_str(&file_conf.punch_model)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
let use_channel_type = UseChannelType::from_str(&file_conf.use_channel)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
|
||||
let config = Config::new(
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
file_conf.tap,
|
||||
file_conf.token,
|
||||
file_conf.device_id,
|
||||
file_conf.name,
|
||||
file_conf.server_address,
|
||||
file_conf.dns,
|
||||
file_conf.stun_server,
|
||||
in_ips,
|
||||
out_ips,
|
||||
file_conf.password,
|
||||
file_conf.mtu,
|
||||
file_conf.tcp,
|
||||
virtual_ip,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
file_conf.no_proxy,
|
||||
file_conf.server_encrypt,
|
||||
file_conf.parallel,
|
||||
cipher_model,
|
||||
file_conf.finger,
|
||||
punch_model,
|
||||
file_conf.ports,
|
||||
file_conf.first_latency,
|
||||
file_conf.device_name,
|
||||
use_channel_type,
|
||||
file_conf.packet_loss,
|
||||
file_conf.packet_delay,
|
||||
)
|
||||
.unwrap();
|
||||
Ok((config, file_conf.cmd))
|
||||
#[cfg(not(feature = "file_config"))]
|
||||
pub fn read_config(_file_path: &str) -> anyhow::Result<(vnt::core::Config, bool)> {
|
||||
unimplemented!()
|
||||
}
|
||||
|
||||
pub fn get_device_id() -> String {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use console::{style, Style};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use crate::command::entity::{DeviceItem, Info, RouteItem};
|
||||
|
||||
@@ -9,10 +10,15 @@ pub fn console_info(status: Info) {
|
||||
println!("Virtual ip: {}", style(status.virtual_ip).green());
|
||||
println!("Virtual gateway: {}", style(status.virtual_gateway).green());
|
||||
println!("Virtual netmask: {}", style(status.virtual_netmask).green());
|
||||
println!(
|
||||
"Connection status: {}",
|
||||
style(status.connect_status).green()
|
||||
);
|
||||
if status.connect_status.eq_ignore_ascii_case("Connected") {
|
||||
println!(
|
||||
"Connection status: {}",
|
||||
style(status.connect_status).green()
|
||||
);
|
||||
} else {
|
||||
println!("Connection status: {}", style(status.connect_status).red());
|
||||
}
|
||||
|
||||
println!("NAT type: {}", style(status.nat_type).green());
|
||||
println!("Relay server: {}", style(status.relay_server).green());
|
||||
println!("Public ips: {}", style(status.public_ips).green());
|
||||
@@ -20,6 +26,38 @@ pub fn console_info(status: Info) {
|
||||
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!("------------------------------------------");
|
||||
println!("Port mapping {}", status.port_mapping_list.len());
|
||||
for (is_tcp, addr, dest) in status.port_mapping_list {
|
||||
if is_tcp {
|
||||
println!(" TCP: {} -> {}", addr, dest)
|
||||
} else {
|
||||
println!(" UDP: {} -> {}", addr, dest)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !status.in_ips.is_empty() || !status.out_ips.is_empty() {
|
||||
println!("------------------------------------------");
|
||||
}
|
||||
if !status.in_ips.is_empty() {
|
||||
println!("IP forwarding {}", status.in_ips.len());
|
||||
for (dest, mask, ip) in status.in_ips {
|
||||
println!(
|
||||
" -- {} --> {}/{}",
|
||||
ip,
|
||||
Ipv4Addr::from(dest),
|
||||
mask.count_ones()
|
||||
)
|
||||
}
|
||||
}
|
||||
if !status.out_ips.is_empty() {
|
||||
println!("Allows network {}", status.out_ips.len());
|
||||
for (dest, mask) in status.out_ips {
|
||||
println!(" {}/{}", Ipv4Addr::from(dest), mask.count_ones())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn convert(num: u64) -> String {
|
||||
|
||||
+149
-98
@@ -1,7 +1,8 @@
|
||||
use anyhow::anyhow;
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
use std::{io, thread};
|
||||
|
||||
use console::style;
|
||||
use getopts::Options;
|
||||
@@ -10,10 +11,13 @@ use common::args_parse::{ips_parse, out_ips_parse};
|
||||
use vnt::channel::punch::PunchModel;
|
||||
use vnt::channel::UseChannelType;
|
||||
use vnt::cipher::CipherModel;
|
||||
use vnt::compression::Compressor;
|
||||
use vnt::core::{Config, Vnt};
|
||||
|
||||
#[cfg(feature = "command")]
|
||||
mod command;
|
||||
mod config;
|
||||
#[cfg(feature = "command")]
|
||||
mod console_out;
|
||||
mod generated_serial_number;
|
||||
mod root_check;
|
||||
@@ -41,6 +45,7 @@ pub fn app_home() -> io::Result<PathBuf> {
|
||||
}
|
||||
|
||||
fn main() {
|
||||
#[cfg(feature = "log")]
|
||||
let _ = log4rs::init_file("log4rs.yaml", Default::default());
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let program = args[0].clone();
|
||||
@@ -73,7 +78,9 @@ fn main() {
|
||||
opts.optopt("", "packet-loss", "丢包率", "<packet-loss>");
|
||||
opts.optopt("", "packet-delay", "延迟", "<packet-delay>");
|
||||
opts.optmulti("", "dns", "dns", "<dns>");
|
||||
opts.optmulti("", "mapping", "mapping", "<mapping>");
|
||||
opts.optopt("f", "", "配置文件", "<conf>");
|
||||
opts.optopt("", "compressor", "压缩算法", "<lz4>");
|
||||
//"后台运行时,查看其他设备列表"
|
||||
opts.optflag("", "list", "后台运行时,查看其他设备列表");
|
||||
opts.optflag("", "all", "后台运行时,查看其他设备完整信息");
|
||||
@@ -99,6 +106,7 @@ fn main() {
|
||||
sudo::escalate_if_needed().unwrap();
|
||||
return;
|
||||
}
|
||||
#[cfg(feature = "command")]
|
||||
if matches.opt_present("list") {
|
||||
command::command(command::CommandEnum::List);
|
||||
return;
|
||||
@@ -130,7 +138,7 @@ fn main() {
|
||||
println!("parameter -k not found .");
|
||||
return;
|
||||
}
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
let tap = matches.opt_present("a");
|
||||
let device_name = matches.opt_str("nic");
|
||||
let token: String = matches.opt_get("k").unwrap().unwrap();
|
||||
@@ -156,7 +164,7 @@ fn main() {
|
||||
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.qq.com:3478".to_string());
|
||||
stun_server.push("stun.miwifi.com:3478".to_string());
|
||||
}
|
||||
let dns = matches.opt_strs("dns");
|
||||
let in_ip = matches.opt_strs("i");
|
||||
@@ -225,19 +233,6 @@ fn main() {
|
||||
|
||||
let cipher_model = match matches.opt_get::<CipherModel>("model") {
|
||||
Ok(model) => {
|
||||
#[cfg(not(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)))]
|
||||
{
|
||||
if password.is_some() && model.is_none() {
|
||||
println!("Encryption not supported");
|
||||
return;
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(feature = "aes_gcm", feature = "server_encrypt")))]
|
||||
{
|
||||
if password.is_some() && model.is_none() {
|
||||
@@ -287,8 +282,17 @@ fn main() {
|
||||
.opt_get::<u32>("packet-delay")
|
||||
.expect("--packet-delay")
|
||||
.unwrap_or(0);
|
||||
#[cfg(feature = "port_mapping")]
|
||||
let port_mapping_list = matches.opt_strs("mapping");
|
||||
let compressor = if let Some(compressor) = matches.opt_str("compressor").as_ref() {
|
||||
Compressor::from_str(compressor)
|
||||
.map_err(|e| anyhow!("{}", e))
|
||||
.unwrap()
|
||||
} else {
|
||||
Compressor::None
|
||||
};
|
||||
let config = match Config::new(
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
tap,
|
||||
token,
|
||||
device_id,
|
||||
@@ -315,10 +319,13 @@ fn main() {
|
||||
use_channel_type,
|
||||
packet_loss,
|
||||
packet_delay,
|
||||
#[cfg(feature = "port_mapping")]
|
||||
port_mapping_list,
|
||||
compressor,
|
||||
) {
|
||||
Ok(config) => config,
|
||||
Err(e) => {
|
||||
println!("config error: {}", e);
|
||||
println!("config.toml error: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -337,38 +344,74 @@ fn main() {
|
||||
|
||||
mod callback;
|
||||
|
||||
fn main0(config: Config, show_cmd: bool) {
|
||||
fn main0(config: Config, _show_cmd: bool) {
|
||||
#[cfg(feature = "port_mapping")]
|
||||
for (is_tcp, addr, dest) in config.port_mapping_list.iter() {
|
||||
if *is_tcp {
|
||||
println!("TCP port mapping {}->{}", addr, dest)
|
||||
} else {
|
||||
println!("UDP port mapping {}->{}", addr, dest)
|
||||
}
|
||||
}
|
||||
let vnt_util = Vnt::new(config, callback::VntHandler {}).unwrap();
|
||||
let vnt_c = vnt_util.clone();
|
||||
thread::Builder::new()
|
||||
.name("CommandServer".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = command::server::CommandServer::new().start(vnt_c) {
|
||||
log::warn!("cmd:{:?}", e);
|
||||
}
|
||||
})
|
||||
.expect("CommandServer");
|
||||
if show_cmd {
|
||||
let mut cmd = String::new();
|
||||
loop {
|
||||
cmd.clear();
|
||||
println!("======== input:list,info,route,all,stop ========");
|
||||
match io::stdin().read_line(&mut cmd) {
|
||||
Ok(len) => {
|
||||
if !command(&cmd[..len], &vnt_util) {
|
||||
#[cfg(any(target_os = "linux", target_os = "macos"))]
|
||||
{
|
||||
let vnt_c = vnt_util.clone();
|
||||
let mut signals = signal_hook::iterator::Signals::new(&[
|
||||
signal_hook::consts::SIGINT,
|
||||
signal_hook::consts::SIGTERM,
|
||||
])
|
||||
.unwrap();
|
||||
let handle = signals.handle();
|
||||
std::thread::spawn(move || {
|
||||
for sig in signals.forever() {
|
||||
match sig {
|
||||
signal_hook::consts::SIGINT | signal_hook::consts::SIGTERM => {
|
||||
println!("Received SIGINT, {}", sig);
|
||||
vnt_c.stop();
|
||||
handle.close();
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("input err:{}", e);
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
#[cfg(feature = "command")]
|
||||
{
|
||||
let vnt_c = vnt_util.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("CommandServer".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = command::server::CommandServer::new().start(vnt_c) {
|
||||
log::warn!("cmd:{:?}", e);
|
||||
}
|
||||
})
|
||||
.expect("CommandServer");
|
||||
if _show_cmd {
|
||||
let mut cmd = String::new();
|
||||
loop {
|
||||
cmd.clear();
|
||||
println!("======== input:list,info,route,all,stop ========");
|
||||
match io::stdin().read_line(&mut cmd) {
|
||||
Ok(len) => {
|
||||
if !command(&cmd[..len], &vnt_util) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("input err:{}", e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
vnt_util.wait()
|
||||
}
|
||||
|
||||
#[cfg(feature = "command")]
|
||||
fn command(cmd: &str, vnt: &Vnt) -> bool {
|
||||
if cmd.is_empty() {
|
||||
return false;
|
||||
@@ -412,58 +455,53 @@ fn print_usage(program: &str, _opts: Options) {
|
||||
println!(" -n <name> 给设备一个名字,便于区分不同设备,默认使用系统版本");
|
||||
println!(" -d <id> 设备唯一标识符,不使用--ip参数时,服务端凭此参数分配虚拟ip,注意不能重复");
|
||||
println!(" -s <server> 注册和中继服务器地址,以'TXT:'开头表示解析TXT记录");
|
||||
println!(" -e <stun-server> stun服务器,用于探测NAT类型,可多次指定,如-e addr1 -e addr2");
|
||||
println!(" -a 使用tap模式,默认使用tun模式");
|
||||
println!(" -e <stun-server> stun服务器,用于探测NAT类型,可使用多个地址,如-e stun1.l.google.com -e stun2.l.google.com");
|
||||
#[cfg(target_os = "windows")]
|
||||
println!(
|
||||
" -a 使用tap模式,默认使用tun模式,使用tap时需要配合'--nic'参数指定tap网卡"
|
||||
);
|
||||
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,可指定多个网段");
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
println!(" -o <out-ip> 配置点对网时使用,-o 192.168.0.0/24表示允许将数据转发到192.168.0.0/24,可指定多个网段");
|
||||
#[cfg(not(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)))]
|
||||
let enums = String::new();
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
|
||||
println!(" -w <password> 使用该密码生成的密钥对客户端数据进行加密,并且服务端无法解密,使用相同密码的客户端才能通信");
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
println!(" -W 加密当前客户端和服务端通信的数据,请留意服务端指纹是否正确");
|
||||
println!(" -u <mtu> 自定义mtu(不加密默认为1450,加密默认为1410)");
|
||||
#[cfg(feature = "file_config")]
|
||||
println!(" -f <conf_file> 读取配置文件中的配置");
|
||||
|
||||
println!(" --tcp 和服务端使用tcp通信,默认使用udp,遇到udp qos时可指定使用tcp");
|
||||
println!(" --ip <ip> 指定虚拟ip,指定的ip不能和其他设备重复,必须有效并且在服务端所属网段下,默认情况由服务端分配");
|
||||
println!(" --par <parallel> 任务并行度(必须为正整数),默认值为1");
|
||||
let mut enums = String::new();
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
enums.push_str("/aes_gcm");
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
enums.push_str("/chacha20_poly1305/chacha20");
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
enums.push_str("/aes_cbc");
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
enums.push_str("/aes_ecb");
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
enums.push_str("/sm4_cbc");
|
||||
if !enums.is_empty() {
|
||||
println!(" -w <password> 使用该密码生成的密钥对客户端数据进行加密,并且服务端无法解密,使用相同密码的客户端才能通信");
|
||||
}
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
println!(" -W 加密当前客户端和服务端通信的数据,请留意服务端指纹是否正确");
|
||||
println!(" -u <mtu> 自定义mtu(不加密默认为1450,加密默认为1410)");
|
||||
println!(" -f <conf_file> 读取配置文件中的配置");
|
||||
|
||||
println!(" --tcp 和服务端使用tcp通信,默认使用udp,遇到udp qos时可指定使用tcp");
|
||||
println!(" --ip <ip> 指定虚拟ip,指定的ip不能和其他设备重复,必须有效并且在服务端所属网段下,默认情况由服务端分配");
|
||||
println!(" --par <parallel> 任务并行度(必须为正整数),默认值为1");
|
||||
if !enums.is_empty() {
|
||||
println!(
|
||||
" --model <model> 加密模式(默认aes_gcm),可选值{}",
|
||||
&enums[1..]
|
||||
);
|
||||
}
|
||||
if !enums.is_empty() {
|
||||
println!(" --finger 增加数据指纹校验,可增加安全性,如果服务端开启指纹校验,则客户端也必须开启");
|
||||
}
|
||||
enums.push_str("/xor");
|
||||
println!(
|
||||
" --model <model> 加密模式(默认aes_gcm),可选值{}",
|
||||
&enums[1..]
|
||||
);
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "chacha20_poly1305",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
println!(" --finger 增加数据指纹校验,可增加安全性,如果服务端开启指纹校验,则客户端也必须开启");
|
||||
println!(" --punch <punch> 取值ipv4/ipv6/all,ipv4表示仅使用ipv4打洞");
|
||||
println!(" --ports <port,port> 取值0~65535,指定本地监听的一组端口,默认监听两个随机端口,使用过多端口会增加网络负担");
|
||||
#[cfg(feature = "command")]
|
||||
println!(" --cmd 开启交互式命令,使用此参数开启控制台输入");
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
println!(" --no-proxy 关闭内置代理,如需点对网则需要配置网卡NAT转发");
|
||||
@@ -475,28 +513,40 @@ fn print_usage(program: &str, _opts: Options) {
|
||||
" --packet-delay <0> 模拟延迟,整数,单位毫秒(ms),程序会按设定的值延迟发包,可用于模拟弱网"
|
||||
);
|
||||
println!(" --dns <host:port> DNS服务器地址,可使用多个dns,不指定时使用系统解析");
|
||||
|
||||
#[cfg(feature = "port_mapping")]
|
||||
println!(" --mapping <mapping> 端口映射,例如 --mapping udp:0.0.0.0:80->10.26.0.10:80 --mapping tcp:0.0.0.0:80->10.26.0.10:80");
|
||||
#[cfg(all(feature = "lz4", feature = "zstd"))]
|
||||
println!(" --compressor <lz4> 启用压缩,可选值lz4/zstd<,level>,level为压缩级别,例如 --compressor lz4 或--compressor zstd,10");
|
||||
#[cfg(feature = "lz4")]
|
||||
#[cfg(not(feature = "zstd"))]
|
||||
println!(" --compressor <lz4> 启用压缩,可选值lz4,例如 --compressor lz4");
|
||||
#[cfg(feature = "zstd")]
|
||||
#[cfg(not(feature = "lz4"))]
|
||||
println!(" --compressor <zstd> 启用压缩,可选值zstd<,level>,level为压缩级别,例如 --compressor zstd,10");
|
||||
println!();
|
||||
println!(
|
||||
" --list {}",
|
||||
yellow("后台运行时,查看其他设备列表".to_string())
|
||||
);
|
||||
println!(
|
||||
" --all {}",
|
||||
yellow("后台运行时,查看其他设备完整信息".to_string())
|
||||
);
|
||||
println!(
|
||||
" --info {}",
|
||||
yellow("后台运行时,查看当前设备信息".to_string())
|
||||
);
|
||||
println!(
|
||||
" --route {}",
|
||||
yellow("后台运行时,查看数据转发路径".to_string())
|
||||
);
|
||||
println!(
|
||||
" --stop {}",
|
||||
yellow("停止后台运行".to_string())
|
||||
);
|
||||
#[cfg(feature = "command")]
|
||||
{
|
||||
println!(
|
||||
" --list {}",
|
||||
yellow("后台运行时,查看其他设备列表".to_string())
|
||||
);
|
||||
println!(
|
||||
" --all {}",
|
||||
yellow("后台运行时,查看其他设备完整信息".to_string())
|
||||
);
|
||||
println!(
|
||||
" --info {}",
|
||||
yellow("后台运行时,查看当前设备信息".to_string())
|
||||
);
|
||||
println!(
|
||||
" --route {}",
|
||||
yellow("后台运行时,查看数据转发路径".to_string())
|
||||
);
|
||||
println!(
|
||||
" --stop {}",
|
||||
yellow("停止后台运行".to_string())
|
||||
);
|
||||
}
|
||||
println!(" -h, --help 帮助");
|
||||
}
|
||||
|
||||
@@ -504,6 +554,7 @@ fn green(str: String) -> impl std::fmt::Display {
|
||||
style(str).green()
|
||||
}
|
||||
|
||||
#[cfg(feature = "command")]
|
||||
fn yellow(str: String) -> impl std::fmt::Display {
|
||||
style(str).yellow()
|
||||
}
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "vnt-jni"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
@@ -14,5 +14,8 @@ jni = { version = "0.21.1", default-features = false }
|
||||
log = "0.4.20"
|
||||
spki = { version = "0.7.2", features = ["fingerprint", "alloc","base64","pem"]}
|
||||
|
||||
[target.'cfg(target_os = "android")'.dependencies]
|
||||
android_logger = "0.13"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "cdylib"]
|
||||
@@ -1,13 +1,16 @@
|
||||
package top.wherewego.vnt.jni;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 启动配置
|
||||
*
|
||||
* @author https://github.com/lbl8603/vnt
|
||||
*/
|
||||
public class Config {
|
||||
public class Config implements Serializable {
|
||||
/**
|
||||
* 是否是tap模式,仅支持windows和linux
|
||||
* 是否是tap模式,仅支持windows
|
||||
*/
|
||||
private boolean tap;
|
||||
/**
|
||||
@@ -38,10 +41,6 @@ public class Config {
|
||||
* 是否开启服务端加密
|
||||
*/
|
||||
private boolean serverEncrypt;
|
||||
/**
|
||||
* 仅使用中继转发
|
||||
*/
|
||||
private boolean relay;
|
||||
/**
|
||||
* 设备id,请使用唯一值
|
||||
*/
|
||||
@@ -54,6 +53,10 @@ public class Config {
|
||||
* dns地址
|
||||
*/
|
||||
private String[] dns;
|
||||
/**
|
||||
* 端口映射
|
||||
*/
|
||||
private String[] portMapping;
|
||||
/**
|
||||
* stun服务地址
|
||||
*/
|
||||
@@ -170,13 +173,6 @@ public class Config {
|
||||
this.serverEncrypt = serverEncrypt;
|
||||
}
|
||||
|
||||
public boolean isRelay() {
|
||||
return relay;
|
||||
}
|
||||
|
||||
public void setRelay(boolean relay) {
|
||||
this.relay = relay;
|
||||
}
|
||||
|
||||
public String getDeviceId() {
|
||||
return deviceId;
|
||||
@@ -201,6 +197,13 @@ public class Config {
|
||||
public void setDns(String[] dns) {
|
||||
this.dns = dns;
|
||||
}
|
||||
public String[] getPortMapping() {
|
||||
return portMapping;
|
||||
}
|
||||
|
||||
public void setPortMapping(String[] portMapping) {
|
||||
this.portMapping = portMapping;
|
||||
}
|
||||
|
||||
public String[] getStunServer() {
|
||||
return stunServer;
|
||||
@@ -297,4 +300,34 @@ public class Config {
|
||||
public void setPacketDelay(Integer packetDelay) {
|
||||
this.packetDelay = packetDelay;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Config{" +
|
||||
"tap=" + tap +
|
||||
", token='" + token + '\'' +
|
||||
", name='" + name + '\'' +
|
||||
", password='" + password + '\'' +
|
||||
", cipherModel='" + cipherModel + '\'' +
|
||||
", punchModel='" + punchModel + '\'' +
|
||||
", mtu=" + mtu +
|
||||
", serverEncrypt=" + serverEncrypt +
|
||||
", deviceId='" + deviceId + '\'' +
|
||||
", server='" + server + '\'' +
|
||||
", dns=" + Arrays.toString(dns) +
|
||||
", portMapping=" + Arrays.toString(portMapping) +
|
||||
", stunServer=" + Arrays.toString(stunServer) +
|
||||
", tcp=" + tcp +
|
||||
", ip='" + ip + '\'' +
|
||||
", finger=" + finger +
|
||||
", firstLatency=" + firstLatency +
|
||||
", inIps=" + Arrays.toString(inIps) +
|
||||
", outIps=" + Arrays.toString(outIps) +
|
||||
", ports=" + Arrays.toString(ports) +
|
||||
", deviceName='" + deviceName + '\'' +
|
||||
", useChannel='" + useChannel + '\'' +
|
||||
", packetLossRate=" + packetLossRate +
|
||||
", packetDelay=" + packetDelay +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import java.io.IOException;
|
||||
public class Vnt implements Closeable {
|
||||
private final long raw;
|
||||
|
||||
public Vnt(Config config, CallBack callBack) throws Exception{
|
||||
public Vnt(Config config, CallBack callBack) throws Exception {
|
||||
this.raw = new0(config, callBack);
|
||||
if (this.raw == 0) {
|
||||
throw new RuntimeException();
|
||||
@@ -26,6 +26,10 @@ public class Vnt implements Closeable {
|
||||
wait0(raw);
|
||||
}
|
||||
|
||||
public boolean awaitTimeout(long ms) {
|
||||
return waitTimeout0(raw, ms);
|
||||
}
|
||||
|
||||
public PeerRouteInfo[] list() {
|
||||
return list0(raw);
|
||||
}
|
||||
@@ -36,6 +40,8 @@ public class Vnt implements Closeable {
|
||||
|
||||
private native void wait0(long raw);
|
||||
|
||||
private native boolean waitTimeout0(long raw, long ms);
|
||||
|
||||
private native void drop0(long raw);
|
||||
|
||||
private native PeerRouteInfo[] list0(long raw);
|
||||
|
||||
@@ -7,12 +7,13 @@ use jni::JNIEnv;
|
||||
use vnt::channel::punch::PunchModel;
|
||||
use vnt::channel::UseChannelType;
|
||||
use vnt::cipher::CipherModel;
|
||||
use vnt::compression::Compressor;
|
||||
use vnt::core::Config;
|
||||
|
||||
use crate::utils::*;
|
||||
|
||||
pub fn new_config(env: &mut JNIEnv, config: JObject) -> Result<Config, Error> {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
let tap = env.get_field(&config, "tap", "Z")?.z()?;
|
||||
let token = to_string_not_null(env, &config, "token")?;
|
||||
let name = to_string_not_null(env, &config, "name")?;
|
||||
@@ -21,6 +22,7 @@ pub fn new_config(env: &mut JNIEnv, config: JObject) -> Result<Config, Error> {
|
||||
let server_address_str = to_string_not_null(env, &config, "server")?;
|
||||
let stun_server = to_string_array_not_null(env, &config, "stunServer")?;
|
||||
let dns = to_string_array(env, &config, "dns")?.unwrap_or_else(|| vec![]);
|
||||
let port_mapping = to_string_array(env, &config, "portMapping")?.unwrap_or_else(|| vec![]);
|
||||
let cipher_model = to_string_not_null(env, &config, "cipherModel")?;
|
||||
let punch_model = to_string(env, &config, "punchModel")?;
|
||||
let mtu = to_integer(env, &config, "mtu")?.map(|v| v as u32);
|
||||
@@ -89,7 +91,7 @@ pub fn new_config(env: &mut JNIEnv, config: JObject) -> Result<Config, Error> {
|
||||
#[cfg(not(target_os = "android"))]
|
||||
let device_name = to_string(env, &config, "deviceName")?;
|
||||
let config = match Config::new(
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
tap,
|
||||
token,
|
||||
device_id,
|
||||
@@ -116,12 +118,14 @@ pub fn new_config(env: &mut JNIEnv, config: JObject) -> Result<Config, Error> {
|
||||
UseChannelType::from_str(&use_channel.unwrap_or_default()).unwrap_or_default(),
|
||||
packet_loss_rate,
|
||||
packet_delay,
|
||||
port_mapping,
|
||||
Compressor::None,
|
||||
) {
|
||||
Ok(config) => config,
|
||||
Err(e) => {
|
||||
env.throw_new(
|
||||
"java/lang/RuntimeException",
|
||||
format!("vnt start error {}", e),
|
||||
format!("vnt start error {:?}", e),
|
||||
)
|
||||
.expect("throw");
|
||||
return Err(Error::JavaException);
|
||||
|
||||
@@ -2,3 +2,4 @@ pub mod callback;
|
||||
pub mod config;
|
||||
pub mod utils;
|
||||
pub mod vnt;
|
||||
pub(crate) mod vnt_logger;
|
||||
|
||||
+13
-2
@@ -1,8 +1,9 @@
|
||||
use std::ptr;
|
||||
use std::time::Duration;
|
||||
|
||||
use jni::errors::Error;
|
||||
use jni::objects::{JClass, JObject, JValue};
|
||||
use jni::sys::{jint, jlong, jobject, jobjectArray, jsize};
|
||||
use jni::sys::{jboolean, jint, jlong, jobject, jobjectArray, jsize};
|
||||
use jni::JNIEnv;
|
||||
|
||||
use vnt::channel::Route;
|
||||
@@ -10,7 +11,6 @@ use vnt::core::Vnt;
|
||||
use vnt::handle::PeerDeviceInfo;
|
||||
|
||||
use crate::callback::CallBack;
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn Java_top_wherewego_vnt_jni_Vnt_new0(
|
||||
mut env: JNIEnv<'static>,
|
||||
@@ -18,6 +18,7 @@ pub unsafe extern "C" fn Java_top_wherewego_vnt_jni_Vnt_new0(
|
||||
config: JObject,
|
||||
call_back: JObject<'static>,
|
||||
) -> jlong {
|
||||
crate::vnt_logger::init_log();
|
||||
let jvm = if let Ok(jvm) = env.get_java_vm() {
|
||||
jvm
|
||||
} else {
|
||||
@@ -74,6 +75,16 @@ pub unsafe extern "C" fn Java_top_wherewego_vnt_jni_Vnt_wait0(
|
||||
let vnt = raw_vnt as *mut Vnt;
|
||||
let _ = (&*vnt).wait();
|
||||
}
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn Java_top_wherewego_vnt_jni_Vnt_waitTimeout0(
|
||||
_env: JNIEnv,
|
||||
_class: JClass,
|
||||
raw_vnt: jlong,
|
||||
time: jlong,
|
||||
) -> jboolean {
|
||||
let vnt = raw_vnt as *mut Vnt;
|
||||
(&*vnt).wait_timeout(Duration::from_millis(time as _)) as _
|
||||
}
|
||||
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn Java_top_wherewego_vnt_jni_Vnt_drop0(
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn init_log() {
|
||||
use android_logger::Config;
|
||||
use log::LevelFilter;
|
||||
android_logger::init_once(
|
||||
Config::default()
|
||||
.with_max_level(LevelFilter::Info) // limit log level
|
||||
.with_tag("vnt_jni"), // logs will show under mytag tag
|
||||
);
|
||||
}
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub fn init_log() {}
|
||||
+29
-17
@@ -1,12 +1,12 @@
|
||||
[package]
|
||||
name = "vnt"
|
||||
version = "1.2.9"
|
||||
version = "1.2.10"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
tun= {path = "tun"}
|
||||
tun = { path = "tun" }
|
||||
packet = { path = "./packet" }
|
||||
bytes = "1.5.0"
|
||||
log = "0.4.17"
|
||||
@@ -19,22 +19,29 @@ sha2 = { version = "0.10.6", features = ["oid"] }
|
||||
thiserror = "1.0.37"
|
||||
protobuf = "3.2.0"
|
||||
socket2 = { version = "0.5.2", features = ["all"] }
|
||||
aes-gcm = { version = "0.10.2",optional = true }
|
||||
aes-gcm = { version = "0.10.2", optional = true }
|
||||
ring = { version = "0.17.0", optional = true }
|
||||
cbc = {version = "0.1.2",optional = true}
|
||||
ecb = {version = "0.1.2",optional = true}
|
||||
cbc = { version = "0.1.2", optional = true }
|
||||
ecb = { version = "0.1.2", optional = true }
|
||||
chacha20poly1305 = { version = "0.10.1", optional = true }
|
||||
chacha20 = { version = "0.9.1", optional = true }
|
||||
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}
|
||||
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 }
|
||||
|
||||
mio = {version = "0.8.10",features = ["os-poll","net"]}
|
||||
mio = { version = "0.8.10", 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 }
|
||||
|
||||
lz4_flex = { version = "0.11", default-features = false, optional = true }
|
||||
zstd = { version = "0.13.1", optional = true }
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
libloading = "0.8.0"
|
||||
|
||||
@@ -42,16 +49,21 @@ libloading = "0.8.0"
|
||||
[build-dependencies]
|
||||
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","ip_proxy"]
|
||||
default = ["server_encrypt", "aes_gcm", "aes_cbc", "aes_ecb", "sm4_cbc", "chacha20_poly1305", "ip_proxy", "port_mapping", "lz4_compress", "zstd_compress"]
|
||||
openssl = ["openssl-sys"]
|
||||
# 从源码编译
|
||||
openssl-vendored = ["openssl-sys/vendored"]
|
||||
ring-cipher = ["ring"]
|
||||
aes_cbc=["cbc"]
|
||||
aes_ecb=["ecb"]
|
||||
sm4_cbc=["libsm"]
|
||||
aes_gcm=["aes-gcm"]
|
||||
server_encrypt =["aes-gcm","rsa","spki"]
|
||||
ip_proxy=[]
|
||||
aes_cbc = ["cbc"]
|
||||
aes_ecb = ["ecb"]
|
||||
sm4_cbc = ["libsm"]
|
||||
aes_gcm = ["aes-gcm"]
|
||||
chacha20_poly1305 = ["chacha20poly1305", "chacha20"]
|
||||
server_encrypt = ["aes-gcm", "rsa", "spki"]
|
||||
ip_proxy = ["tokio"]
|
||||
port_mapping = ["tokio"]
|
||||
lz4_compress = ["lz4_flex"]
|
||||
zstd_compress = ["zstd"]
|
||||
|
||||
@@ -1,4 +1,17 @@
|
||||
use cfg_aliases::cfg_aliases;
|
||||
|
||||
fn main() {
|
||||
cfg_aliases! {
|
||||
cipher: {
|
||||
any(feature = "aes_gcm",
|
||||
feature = "chacha20_poly1305",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)},
|
||||
}
|
||||
|
||||
std::fs::create_dir_all("src/proto").unwrap();
|
||||
protobuf_codegen::Codegen::new()
|
||||
.pure()
|
||||
|
||||
@@ -81,6 +81,9 @@ impl<B: AsRef<[u8]> + AsMut<[u8]>> IpV4Packet<B> {
|
||||
pub fn set_flags(&mut self, flags: u8) {
|
||||
self.buffer.as_mut()[6] = (self.buffer.as_ref()[6] & 0b11100000) | (flags << 5)
|
||||
}
|
||||
pub fn set_ttl(&mut self, ttl: u8) {
|
||||
self.buffer.as_mut()[8] = ttl
|
||||
}
|
||||
fn set_checksum(&mut self, value: u16) {
|
||||
self.header_mut()[10..12].copy_from_slice(&value.to_be_bytes())
|
||||
}
|
||||
|
||||
+11
-11
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV6, UdpSocket};
|
||||
use std::ops::Deref;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{io, thread};
|
||||
@@ -48,7 +48,6 @@ impl ChannelContext {
|
||||
tcp_map: RwLock::new(HashMap::with_capacity(64)),
|
||||
route_table: RouteTable::new(use_channel_type, first_latency, channel_num),
|
||||
is_tcp,
|
||||
state: AtomicBool::new(true),
|
||||
packet_loss_rate,
|
||||
packet_delay,
|
||||
main_index: AtomicUsize::new(0),
|
||||
@@ -86,8 +85,6 @@ pub struct ContextInner {
|
||||
pub route_table: RouteTable,
|
||||
// 是否使用tcp连接服务器
|
||||
is_tcp: bool,
|
||||
//状态
|
||||
state: AtomicBool,
|
||||
//控制丢包率,取值v=[0,100_0000] 丢包率r=v/100_0000
|
||||
packet_loss_rate: u32,
|
||||
//控制延迟
|
||||
@@ -100,12 +97,6 @@ impl ContextInner {
|
||||
pub fn use_channel_type(&self) -> UseChannelType {
|
||||
self.route_table.use_channel_type
|
||||
}
|
||||
pub fn is_stop(&self) -> bool {
|
||||
!self.state.load(Ordering::Acquire)
|
||||
}
|
||||
pub fn stop(&self) {
|
||||
self.state.store(false, Ordering::Release);
|
||||
}
|
||||
/// 通过sub_udp_socket是否为空来判断是否为锥形网络
|
||||
pub fn is_cone(&self) -> bool {
|
||||
self.sub_udp_socket.read().is_empty()
|
||||
@@ -324,7 +315,16 @@ impl RouteTable {
|
||||
} else {
|
||||
let len = v.len();
|
||||
if len != 0 {
|
||||
return Ok(v[index % len].0);
|
||||
let route = &v[index % len].0;
|
||||
// 跳过默认rt的路由(一般是刚加入的),这有助于提升稳定性
|
||||
if route.rt != DEFAULT_RT {
|
||||
return Ok(*route);
|
||||
}
|
||||
for (route, _) in v {
|
||||
if route.rt != DEFAULT_RT {
|
||||
return Ok(*route);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,5 +2,11 @@ use crate::channel::context::ChannelContext;
|
||||
use crate::channel::RouteKey;
|
||||
|
||||
pub trait RecvChannelHandler: Clone + Send + 'static {
|
||||
fn handle(&mut self, buf: &mut [u8], route_key: RouteKey, context: &ChannelContext);
|
||||
fn handle(
|
||||
&mut self,
|
||||
buf: &mut [u8],
|
||||
extend: &mut [u8],
|
||||
route_key: RouteKey,
|
||||
context: &ChannelContext,
|
||||
);
|
||||
}
|
||||
|
||||
+25
-26
@@ -1,4 +1,4 @@
|
||||
use std::io;
|
||||
use anyhow::Context;
|
||||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::str::FromStr;
|
||||
|
||||
@@ -7,7 +7,7 @@ use crate::channel::handler::RecvChannelHandler;
|
||||
use crate::channel::sender::AcceptSocketSender;
|
||||
use crate::channel::tcp_channel::tcp_listen;
|
||||
use crate::channel::udp_channel::udp_listen;
|
||||
use crate::util::{io_convert, StopManager};
|
||||
use crate::util::StopManager;
|
||||
|
||||
pub mod context;
|
||||
pub mod handler;
|
||||
@@ -18,7 +18,7 @@ pub mod sender;
|
||||
pub mod tcp_channel;
|
||||
pub mod udp_channel;
|
||||
|
||||
const BUFFER_SIZE: usize = 1024 * 16;
|
||||
pub const BUFFER_SIZE: usize = 1024 * 16;
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
pub enum UseChannelType {
|
||||
Relay,
|
||||
@@ -68,7 +68,7 @@ pub struct RouteSortKey {
|
||||
pub metric: u8,
|
||||
pub rt: i64,
|
||||
}
|
||||
const DEFAULT_RT: i64 = 999;
|
||||
const DEFAULT_RT: i64 = 9999;
|
||||
impl Route {
|
||||
pub fn new(is_tcp: bool, index: usize, addr: SocketAddr, metric: u8, rt: i64) -> Self {
|
||||
Self {
|
||||
@@ -145,7 +145,7 @@ pub fn init_context(
|
||||
is_tcp: bool,
|
||||
packet_loss_rate: Option<f64>,
|
||||
packet_delay: u32,
|
||||
) -> io::Result<(ChannelContext, mio::net::TcpListener)> {
|
||||
) -> anyhow::Result<(ChannelContext, mio::net::TcpListener)> {
|
||||
assert!(!ports.is_empty(), "not channel");
|
||||
let mut udps = Vec::with_capacity(ports.len());
|
||||
//检查系统是否支持ipv6
|
||||
@@ -161,9 +161,9 @@ pub fn init_context(
|
||||
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)?;
|
||||
io_convert(socket.set_only_v6(false), |_| {
|
||||
format!("set_only_v6 failed: {}", &address)
|
||||
})?;
|
||||
socket
|
||||
.set_only_v6(false)
|
||||
.with_context(|| format!("set_only_v6 failed: {}", &address))?;
|
||||
(socket, address)
|
||||
} else {
|
||||
let address: SocketAddr = format!("0.0.0.0:{}", port).parse().unwrap();
|
||||
@@ -172,16 +172,15 @@ pub fn init_context(
|
||||
address,
|
||||
)
|
||||
};
|
||||
|
||||
io_convert(socket.set_send_buffer_size(2 * 1024 * 1024), |_| {
|
||||
format!("set_send_buffer_size failed: {}", &address)
|
||||
})?;
|
||||
io_convert(socket.set_recv_buffer_size(2 * 1024 * 1024), |_| {
|
||||
format!("set_recv_buffer_size failed: {}", &address)
|
||||
})?;
|
||||
io_convert(socket.bind(&address.into()), |_| {
|
||||
format!("bind failed: {}", &address)
|
||||
})?;
|
||||
if let Err(e) = socket.set_send_buffer_size(2 * 1024 * 1024) {
|
||||
log::warn!("set_send_buffer_size {:?}", e);
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -200,9 +199,9 @@ pub fn init_context(
|
||||
let (socket, address) = if use_ipv6 {
|
||||
let address: SocketAddr = format!("[::]:{}", port).parse().unwrap();
|
||||
let socket = socket2::Socket::new(socket2::Domain::IPV6, socket2::Type::STREAM, None)?;
|
||||
io_convert(socket.set_only_v6(false), |_| {
|
||||
format!("set_only_v6 failed: {}", &address)
|
||||
})?;
|
||||
socket
|
||||
.set_only_v6(false)
|
||||
.with_context(|| format!("set_only_v6 failed: {}", &address))?;
|
||||
(socket, address)
|
||||
} else {
|
||||
let address: SocketAddr = format!("0.0.0.0:{}", port).parse().unwrap();
|
||||
@@ -219,12 +218,12 @@ pub fn init_context(
|
||||
} else {
|
||||
format!("0.0.0.0:{}", port).parse().unwrap()
|
||||
};
|
||||
io_convert(socket.bind(&address.into()), |_| {
|
||||
format!("bind failed: {}", &address)
|
||||
})?;
|
||||
socket
|
||||
.bind(&address.into())
|
||||
.with_context(|| format!("bind failed: {}", &address))?;
|
||||
} else {
|
||||
//手动指定的ip,直接报错
|
||||
io_convert(Err(e), |_| format!("bind failed: {}", &address))?;
|
||||
Err(anyhow::anyhow!("{:?},bind failed: {}", e, address))?;
|
||||
}
|
||||
}
|
||||
socket.listen(128)?;
|
||||
@@ -239,7 +238,7 @@ pub fn init_channel<H>(
|
||||
context: ChannelContext,
|
||||
stop_manager: StopManager,
|
||||
recv_handler: H,
|
||||
) -> io::Result<(
|
||||
) -> anyhow::Result<(
|
||||
AcceptSocketSender<Option<Vec<mio::net::UdpSocket>>>,
|
||||
AcceptSocketSender<(mio::net::TcpStream, SocketAddr, Option<Vec<u8>>)>,
|
||||
)>
|
||||
|
||||
@@ -103,7 +103,7 @@ impl NatInfo {
|
||||
if port != 0 {
|
||||
if let Some(public_port) = self.public_ports.get_mut(index) {
|
||||
if *public_port != port {
|
||||
log::info!("端口变化={}:{}", ip, port)
|
||||
log::info!("端口变化={}:{} index={}", ip, port, index)
|
||||
}
|
||||
*public_port = port;
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ pub fn tcp_listen<H>(
|
||||
stop_manager: StopManager,
|
||||
recv_handler: H,
|
||||
context: ChannelContext,
|
||||
) -> io::Result<AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>>
|
||||
) -> anyhow::Result<AcceptSocketSender<(TcpStream, SocketAddr, Option<Vec<u8>>)>>
|
||||
where
|
||||
H: RecvChannelHandler,
|
||||
{
|
||||
@@ -75,7 +75,7 @@ fn tcp_listen0<H>(
|
||||
accept_tcp_receiver: Receiver<(TcpStream, SocketAddr, Option<Vec<u8>>)>,
|
||||
mut recv_handler: H,
|
||||
context: ChannelContext,
|
||||
) -> io::Result<()>
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
H: RecvChannelHandler,
|
||||
{
|
||||
@@ -87,6 +87,7 @@ where
|
||||
|
||||
let mut read_map: HashMap<Token, (RouteKey, TcpStream, Box<[u8; BUFFER_SIZE]>, usize)> =
|
||||
HashMap::with_capacity(32);
|
||||
let mut extend = [0; BUFFER_SIZE];
|
||||
loop {
|
||||
poll.poll(&mut events, None)?;
|
||||
for event in events.iter() {
|
||||
@@ -108,7 +109,7 @@ where
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
return Err(e);
|
||||
return Err(e)?;
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -132,9 +133,13 @@ where
|
||||
}
|
||||
token => {
|
||||
if event.is_readable() {
|
||||
if let Err(e) =
|
||||
readable_handle(&token, &mut read_map, &mut recv_handler, &context)
|
||||
{
|
||||
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) {
|
||||
@@ -159,7 +164,7 @@ fn init_writable_handler(
|
||||
receiver: Receiver<(TcpStream, Token, SocketAddr, Option<Vec<u8>>)>,
|
||||
stop_manager: StopManager,
|
||||
context: ChannelContext,
|
||||
) -> io::Result<WritableNotify> {
|
||||
) -> anyhow::Result<WritableNotify> {
|
||||
let poll = Poll::new()?;
|
||||
let writable_notify = WritableNotify::new(Waker::new(poll.registry(), NOTIFY)?);
|
||||
let worker = {
|
||||
@@ -339,6 +344,7 @@ fn readable_handle<H>(
|
||||
map: &mut HashMap<Token, (RouteKey, TcpStream, Box<[u8; BUFFER_SIZE]>, usize)>,
|
||||
recv_handler: &mut H,
|
||||
context: &ChannelContext,
|
||||
extend: &mut [u8],
|
||||
) -> io::Result<()>
|
||||
where
|
||||
H: RecvChannelHandler,
|
||||
@@ -360,7 +366,7 @@ where
|
||||
}
|
||||
*begin += len;
|
||||
if end > 4 && *begin == end {
|
||||
recv_handler.handle(&mut buf[4..end], *route_key, context);
|
||||
recv_handler.handle(&mut buf[4..end], extend, *route_key, context);
|
||||
*begin = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ pub fn udp_listen<H>(
|
||||
stop_manager: StopManager,
|
||||
recv_handler: H,
|
||||
context: ChannelContext,
|
||||
) -> io::Result<AcceptSocketSender<Option<Vec<UdpSocket>>>>
|
||||
) -> anyhow::Result<AcceptSocketSender<Option<Vec<UdpSocket>>>>
|
||||
where
|
||||
H: RecvChannelHandler,
|
||||
{
|
||||
@@ -31,7 +31,7 @@ fn sub_udp_listen<H>(
|
||||
stop_manager: StopManager,
|
||||
recv_handler: H,
|
||||
context: ChannelContext,
|
||||
) -> io::Result<AcceptSocketSender<Option<Vec<UdpSocket>>>>
|
||||
) -> anyhow::Result<AcceptSocketSender<Option<Vec<UdpSocket>>>>
|
||||
where
|
||||
H: RecvChannelHandler,
|
||||
{
|
||||
@@ -70,6 +70,7 @@ 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);
|
||||
loop {
|
||||
poll.poll(&mut events, None)?;
|
||||
@@ -115,6 +116,7 @@ where
|
||||
Ok((len, addr)) => {
|
||||
recv_handler.handle(
|
||||
&mut buf[..len],
|
||||
&mut extend,
|
||||
RouteKey::new(false, token.0, addr),
|
||||
&context,
|
||||
);
|
||||
@@ -206,7 +208,7 @@ fn main_udp_listen<H>(
|
||||
stop_manager: StopManager,
|
||||
recv_handler: H,
|
||||
context: ChannelContext,
|
||||
) -> io::Result<()>
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
H: RecvChannelHandler,
|
||||
{
|
||||
@@ -252,6 +254,7 @@ where
|
||||
}
|
||||
|
||||
let mut events = Events::with_capacity(udps.len());
|
||||
let mut extend = [0; BUFFER_SIZE];
|
||||
loop {
|
||||
poll.poll(&mut events, None)?;
|
||||
for x in events.iter() {
|
||||
@@ -270,6 +273,7 @@ where
|
||||
Ok((len, addr)) => {
|
||||
recv_handler.handle(
|
||||
&mut buf[..len],
|
||||
&mut extend,
|
||||
RouteKey::new(false, index, addr),
|
||||
&context,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
mod rs_aes_cbc;
|
||||
pub use rs_aes_cbc::*;
|
||||
@@ -1,6 +1,5 @@
|
||||
use std::io;
|
||||
|
||||
use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyIvInit};
|
||||
use anyhow::anyhow;
|
||||
use rand::RngCore;
|
||||
|
||||
use crate::cipher::Finger;
|
||||
@@ -50,14 +49,14 @@ impl AesCbcCipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not encrypt"));
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
if net_packet.payload().len() < 16 {
|
||||
log::error!("数据异常,长度{}小于{}", net_packet.payload().len(), 16);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("aes_cbc data err"));
|
||||
}
|
||||
let mut iv = [0; 16];
|
||||
iv[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
@@ -75,7 +74,7 @@ impl AesCbcCipher {
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&iv[..12], secret_body.en_body());
|
||||
if &finger != secret_body.finger() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "finger err"));
|
||||
return Err(anyhow!("aes_cbc finger err"));
|
||||
}
|
||||
}
|
||||
let rs = match &self.cipher {
|
||||
@@ -92,10 +91,7 @@ impl AesCbcCipher {
|
||||
net_packet.set_data_len(HEAD_LEN + len - 4)?;
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("解密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("aes_cbc 解密失败:{}", e)),
|
||||
}
|
||||
}
|
||||
/// net_packet 必须预留足够长度
|
||||
@@ -103,7 +99,7 @@ impl AesCbcCipher {
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let data_len = net_packet.data_len();
|
||||
let mut iv = [0; 16];
|
||||
iv[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
@@ -146,10 +142,7 @@ impl AesCbcCipher {
|
||||
net_packet.set_encrypt_flag(true);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("加密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("aes_cbc 加密失败:{}", e)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#[cfg(not(any(feature = "openssl-vendored", feature = "openssl")))]
|
||||
mod rs_aes_ecb;
|
||||
#[cfg(not(any(feature = "openssl-vendored", feature = "openssl")))]
|
||||
pub use rs_aes_ecb::*;
|
||||
|
||||
#[cfg(any(feature = "openssl-vendored", feature = "openssl"))]
|
||||
mod openssl_aes_ecb;
|
||||
#[cfg(any(feature = "openssl-vendored", feature = "openssl"))]
|
||||
pub use openssl_aes_ecb::*;
|
||||
@@ -1,8 +1,11 @@
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::{NetPacket, HEAD_LEN};
|
||||
use std::ptr;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use libc::c_int;
|
||||
use openssl_sys::EVP_CIPHER_CTX;
|
||||
use std::{io, ptr};
|
||||
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::{NetPacket, HEAD_LEN};
|
||||
|
||||
pub struct AesEcbCipher {
|
||||
key: Vec<u8>,
|
||||
@@ -100,10 +103,10 @@ impl AesEcbCipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not encrypt"));
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
|
||||
if let Some(finger) = &self.finger {
|
||||
@@ -116,18 +119,18 @@ impl AesEcbCipher {
|
||||
nonce_raw[11] = net_packet.source_ttl();
|
||||
let len = net_packet.payload().len();
|
||||
if len < 12 {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data len err"));
|
||||
return Err(anyhow!("data len err"));
|
||||
}
|
||||
let secret_body = &net_packet.payload()[..len - 12];
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body);
|
||||
if &finger != &net_packet.payload()[len - 12..] {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "finger err"));
|
||||
return Err(anyhow!("finger err"));
|
||||
}
|
||||
net_packet.set_data_len(net_packet.data_len() - finger.len())?;
|
||||
}
|
||||
if net_packet.payload().len() < 16 {
|
||||
log::error!("数据异常,长度{}小于{}", net_packet.payload().len(), 16);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let input = net_packet.payload();
|
||||
let mut out = [0u8; 1024 * 5];
|
||||
@@ -147,22 +150,22 @@ impl AesEcbCipher {
|
||||
//校验头部
|
||||
let src_net_packet = NetPacket::new(text)?;
|
||||
if src_net_packet.source() != net_packet.source() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.destination() != net_packet.destination() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.protocol() != net_packet.protocol() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.transport_protocol() != net_packet.transport_protocol() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.is_gateway() != net_packet.is_gateway() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.source_ttl() != net_packet.source_ttl() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
}
|
||||
net_packet.set_encrypt_flag(false);
|
||||
@@ -175,7 +178,7 @@ impl AesEcbCipher {
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let input = net_packet.buffer();
|
||||
let mut out = [0u8; 1024 * 5];
|
||||
let mut out_len = 0;
|
||||
@@ -191,7 +194,7 @@ impl AesEcbCipher {
|
||||
}
|
||||
let out_len = out_len as usize;
|
||||
if out_len == 0 {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "ciphertext len err"));
|
||||
return Err(anyhow!("ciphertext len err"));
|
||||
}
|
||||
//密文
|
||||
let ciphertext = &out[..out_len];
|
||||
@@ -1,7 +1,8 @@
|
||||
use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyInit};
|
||||
use anyhow::anyhow;
|
||||
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::{NetPacket, HEAD_LEN};
|
||||
use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyInit};
|
||||
use std::io;
|
||||
|
||||
type Aes128EcbEnc = ecb::Encryptor<aes::Aes128>;
|
||||
type Aes128EcbDec = ecb::Decryptor<aes::Aes128>;
|
||||
@@ -46,10 +47,10 @@ impl AesEcbCipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not encrypt"));
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
|
||||
if let Some(finger) = &self.finger {
|
||||
@@ -62,18 +63,18 @@ impl AesEcbCipher {
|
||||
nonce_raw[11] = net_packet.source_ttl();
|
||||
let len = net_packet.payload().len();
|
||||
if len < 12 {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "payload len <12"));
|
||||
return Err(anyhow!("payload len <12"));
|
||||
}
|
||||
let secret_body = &net_packet.payload()[..len - 12];
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body);
|
||||
if &finger != &net_packet.payload()[len - 12..] {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "finger err"));
|
||||
return Err(anyhow!("finger err"));
|
||||
}
|
||||
net_packet.set_data_len(net_packet.data_len() - finger.len())?;
|
||||
}
|
||||
if net_packet.payload().len() < 16 {
|
||||
log::error!("数据异常,长度{}小于{}", net_packet.payload().len(), 16);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let mut out = [0u8; 1024 * 5];
|
||||
let rs = match self.key {
|
||||
@@ -87,32 +88,29 @@ impl AesEcbCipher {
|
||||
//校验头部
|
||||
let src_net_packet = NetPacket::new(buf)?;
|
||||
if src_net_packet.source() != net_packet.source() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.destination() != net_packet.destination() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.protocol() != net_packet.protocol() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.transport_protocol() != net_packet.transport_protocol() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.is_gateway() != net_packet.is_gateway() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.source_ttl() != net_packet.source_ttl() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
net_packet.set_data_len(buf.len())?;
|
||||
net_packet.set_payload(src_net_packet.payload())?;
|
||||
net_packet.set_encrypt_flag(false);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("aes_ecb解密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("aes_ecb解密失败:{}", e)),
|
||||
}
|
||||
}
|
||||
/// net_packet 必须预留足够长度
|
||||
@@ -120,7 +118,7 @@ impl AesEcbCipher {
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let mut out = [0u8; 1024 * 5];
|
||||
let rs = match self.key {
|
||||
AesEcbEnum::AES128ECB(key) => Aes128EcbEnc::new(&key.into())
|
||||
@@ -152,10 +150,7 @@ impl AesEcbCipher {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("aes_ecb加密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("aes_ecb加密失败:{}", e)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
use std::io;
|
||||
|
||||
use aes_gcm::aead::consts::{U12, U16};
|
||||
use aes_gcm::aead::generic_array::GenericArray;
|
||||
use aes_gcm::{AeadInPlace, Aes128Gcm, Aes256Gcm, Key, KeyInit, Nonce, Tag};
|
||||
use anyhow::anyhow;
|
||||
use rand::RngCore;
|
||||
|
||||
use crate::cipher::finger::Finger;
|
||||
@@ -39,14 +38,14 @@ impl AesGcmCipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not encrypt"));
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
if net_packet.payload().len() < AES_GCM_ENCRYPTION_RESERVED {
|
||||
log::error!("数据异常,长度小于{}", AES_GCM_ENCRYPTION_RESERVED);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
@@ -62,7 +61,7 @@ impl AesGcmCipher {
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body.en_body());
|
||||
if &finger != secret_body.finger() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "finger err"));
|
||||
return Err(anyhow!("finger err"));
|
||||
}
|
||||
}
|
||||
let tag: GenericArray<u8, U16> = Tag::clone_from_slice(tag);
|
||||
@@ -75,10 +74,7 @@ impl AesGcmCipher {
|
||||
}
|
||||
};
|
||||
if let Err(e) = rs {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("解密失败:{}", e),
|
||||
));
|
||||
return Err(anyhow!("解密失败:{}", e));
|
||||
}
|
||||
net_packet.set_encrypt_flag(false);
|
||||
net_packet.set_data_len(net_packet.data_len() - AES_GCM_ENCRYPTION_RESERVED)?;
|
||||
@@ -89,9 +85,9 @@ impl AesGcmCipher {
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if net_packet.reserve() < AES_GCM_ENCRYPTION_RESERVED {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "too short"));
|
||||
return Err(anyhow!("too short"));
|
||||
}
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
@@ -123,10 +119,7 @@ impl AesGcmCipher {
|
||||
net_packet.set_encrypt_flag(true);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("加密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("加密失败:{}", e)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#[cfg(feature = "ring-cipher")]
|
||||
mod ring_aes_gcm_cipher;
|
||||
#[cfg(feature = "ring-cipher")]
|
||||
pub use ring_aes_gcm_cipher::*;
|
||||
|
||||
#[cfg(not(feature = "ring-cipher"))]
|
||||
mod aes_gcm_cipher;
|
||||
#[cfg(not(feature = "ring-cipher"))]
|
||||
pub use aes_gcm_cipher::*;
|
||||
+10
-19
@@ -1,9 +1,9 @@
|
||||
use crate::cipher::Finger;
|
||||
use anyhow::anyhow;
|
||||
use rand::RngCore;
|
||||
use ring::aead;
|
||||
use ring::aead::{LessSafeKey, UnboundKey};
|
||||
use std::io;
|
||||
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::body::{SecretBody, AES_GCM_ENCRYPTION_RESERVED};
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
@@ -53,14 +53,14 @@ impl AesGcmCipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not encrypt"));
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
if net_packet.payload().len() < AES_GCM_ENCRYPTION_RESERVED {
|
||||
log::error!("数据异常,长度小于{}", AES_GCM_ENCRYPTION_RESERVED);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
@@ -74,7 +74,7 @@ impl AesGcmCipher {
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body.en_body());
|
||||
if &finger != secret_body.finger() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "ring aes finger err"));
|
||||
return Err(anyhow!("ring aes finger err"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,10 +87,7 @@ impl AesGcmCipher {
|
||||
}
|
||||
};
|
||||
if let Err(e) = rs {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("解密失败:{}", e),
|
||||
));
|
||||
return Err(anyhow!("解密失败:{}", e));
|
||||
}
|
||||
net_packet.set_encrypt_flag(false);
|
||||
net_packet.set_data_len(net_packet.data_len() - AES_GCM_ENCRYPTION_RESERVED)?;
|
||||
@@ -102,7 +99,7 @@ impl AesGcmCipher {
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
nonce_raw[4..8].copy_from_slice(&net_packet.destination().octets());
|
||||
@@ -128,10 +125,7 @@ impl AesGcmCipher {
|
||||
Ok(tag) => {
|
||||
let tag = tag.as_ref();
|
||||
if tag.len() != 16 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("加密tag长度错误:{}", tag.len()),
|
||||
));
|
||||
return Err(anyhow!("加密tag长度错误:{}", tag.len()));
|
||||
}
|
||||
secret_body.set_tag(tag)?;
|
||||
if let Some(finger) = &self.finger {
|
||||
@@ -141,10 +135,7 @@ impl AesGcmCipher {
|
||||
net_packet.set_encrypt_flag(true);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("加密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("加密失败:{}", e)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
mod rs_chacha20;
|
||||
pub use rs_chacha20::*;
|
||||
@@ -0,0 +1,114 @@
|
||||
use aes::cipher::Iv;
|
||||
use anyhow::anyhow;
|
||||
use chacha20::cipher::{Key, KeyIvInit, StreamCipher};
|
||||
use chacha20::ChaCha20;
|
||||
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::body::ChaCah20SecretBody;
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ChaCha20Cipher {
|
||||
key: [u8; 32],
|
||||
pub(crate) finger: Option<Finger>,
|
||||
}
|
||||
|
||||
impl ChaCha20Cipher {
|
||||
pub fn new_256(key: [u8; 32], finger: Option<Finger>) -> Self {
|
||||
Self { key, finger }
|
||||
}
|
||||
}
|
||||
|
||||
impl ChaCha20Cipher {
|
||||
pub fn key(&self) -> &[u8] {
|
||||
&self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl ChaCha20Cipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
let mut iv = [0; 12];
|
||||
iv[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
iv[4..8].copy_from_slice(&net_packet.destination().octets());
|
||||
iv[8] = net_packet.protocol().into();
|
||||
iv[9] = net_packet.transport_protocol();
|
||||
iv[10] = net_packet.is_gateway() as u8;
|
||||
iv[11] = net_packet.source_ttl();
|
||||
|
||||
let mut secret_body =
|
||||
ChaCah20SecretBody::new(net_packet.payload_mut(), self.finger.is_some())?;
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&iv[..12], secret_body.en_body());
|
||||
if &finger != secret_body.finger() {
|
||||
return Err(anyhow!("ChaCha20 finger err"));
|
||||
}
|
||||
}
|
||||
|
||||
ChaCha20::new(
|
||||
Key::<ChaCha20>::from_slice(&self.key),
|
||||
Iv::<ChaCha20>::from_slice(&iv),
|
||||
)
|
||||
.apply_keystream(secret_body.en_body_mut());
|
||||
let len = secret_body.en_body().len();
|
||||
net_packet.set_encrypt_flag(false);
|
||||
net_packet.set_payload_len(len)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
let data_len = net_packet.data_len();
|
||||
let mut iv = [0; 12];
|
||||
iv[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
iv[4..8].copy_from_slice(&net_packet.destination().octets());
|
||||
iv[8] = net_packet.protocol().into();
|
||||
iv[9] = net_packet.transport_protocol();
|
||||
iv[10] = net_packet.is_gateway() as u8;
|
||||
iv[11] = net_packet.source_ttl();
|
||||
if let Some(_) = &self.finger {
|
||||
net_packet.set_data_len(data_len + 12)?;
|
||||
}
|
||||
let mut secret_body =
|
||||
ChaCah20SecretBody::new(net_packet.payload_mut(), self.finger.is_some())?;
|
||||
ChaCha20::new(
|
||||
Key::<ChaCha20>::from_slice(&self.key),
|
||||
Iv::<ChaCha20>::from_slice(&iv),
|
||||
)
|
||||
.apply_keystream(secret_body.en_body_mut());
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&iv[..12], secret_body.en_body_mut());
|
||||
let mut secret_body = ChaCah20SecretBody::new(net_packet.payload_mut(), true)?;
|
||||
secret_body.set_finger(&finger)?;
|
||||
}
|
||||
|
||||
net_packet.set_encrypt_flag(true);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_chacha20() {
|
||||
let d = ChaCha20Cipher::new_256([0; 32], Some(Finger::new("123")));
|
||||
let mut p =
|
||||
NetPacket::new_encrypt([0; 13 + crate::protocol::body::ENCRYPTION_RESERVED]).unwrap();
|
||||
let src = p.buffer().to_vec();
|
||||
d.encrypt_ipv4(&mut p).unwrap();
|
||||
d.decrypt_ipv4(&mut p).unwrap();
|
||||
assert_eq!(p.buffer(), &src);
|
||||
|
||||
let d = ChaCha20Cipher::new_256([0; 32], None);
|
||||
let mut p =
|
||||
NetPacket::new_encrypt([0; 13 + crate::protocol::body::ENCRYPTION_RESERVED]).unwrap();
|
||||
let src = p.buffer().to_vec();
|
||||
d.encrypt_ipv4(&mut p).unwrap();
|
||||
d.decrypt_ipv4(&mut p).unwrap();
|
||||
assert_eq!(p.buffer(), &src);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
#[cfg(feature = "ring-cipher")]
|
||||
mod ring_chacha20_poly1305;
|
||||
#[cfg(feature = "ring-cipher")]
|
||||
pub use ring_chacha20_poly1305::*;
|
||||
|
||||
#[cfg(not(feature = "ring-cipher"))]
|
||||
mod rs_chacha20_poly1305;
|
||||
#[cfg(not(feature = "ring-cipher"))]
|
||||
pub use rs_chacha20_poly1305::*;
|
||||
@@ -0,0 +1,129 @@
|
||||
use anyhow::anyhow;
|
||||
|
||||
use ring::aead;
|
||||
use ring::aead::{LessSafeKey, UnboundKey};
|
||||
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::body::{SecretBody, AES_GCM_ENCRYPTION_RESERVED};
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ChaCha20Poly1305Cipher {
|
||||
key: Vec<u8>,
|
||||
pub(crate) cipher: LessSafeKey,
|
||||
pub(crate) finger: Option<Finger>,
|
||||
}
|
||||
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
pub fn new_256(key: [u8; 32], finger: Option<Finger>) -> Self {
|
||||
let cipher = LessSafeKey::new(UnboundKey::new(&aead::CHACHA20_POLY1305, &key).unwrap());
|
||||
Self {
|
||||
key: key.to_vec(),
|
||||
cipher,
|
||||
finger,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
pub fn key(&self) -> &[u8] {
|
||||
&self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
if net_packet.payload().len() < AES_GCM_ENCRYPTION_RESERVED {
|
||||
log::error!("数据异常,长度小于{}", AES_GCM_ENCRYPTION_RESERVED);
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
nonce_raw[4..8].copy_from_slice(&net_packet.destination().octets());
|
||||
nonce_raw[8] = net_packet.protocol().into();
|
||||
nonce_raw[9] = net_packet.transport_protocol();
|
||||
nonce_raw[10] = net_packet.is_gateway() as u8;
|
||||
nonce_raw[11] = net_packet.source_ttl();
|
||||
let nonce = aead::Nonce::assume_unique_for_key(nonce_raw);
|
||||
let mut secret_body = SecretBody::new(net_packet.payload_mut(), self.finger.is_some())?;
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body.en_body());
|
||||
if &finger != secret_body.finger() {
|
||||
return Err(anyhow!("ring CHACHA20_POLY1305 finger err"));
|
||||
}
|
||||
}
|
||||
|
||||
let rs = self
|
||||
.cipher
|
||||
.open_in_place(nonce, aead::Aad::empty(), secret_body.en_body_mut());
|
||||
if let Err(e) = rs {
|
||||
return Err(anyhow!("ring CHACHA20_POLY1305 解密失败:{}", e));
|
||||
}
|
||||
net_packet.set_encrypt_flag(false);
|
||||
net_packet.set_data_len(net_packet.data_len() - AES_GCM_ENCRYPTION_RESERVED)?;
|
||||
return Ok(());
|
||||
}
|
||||
/// net_packet 必须预留足够长度
|
||||
/// data_len是有效载荷的长度
|
||||
/// 返回加密后载荷的长度
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
nonce_raw[4..8].copy_from_slice(&net_packet.destination().octets());
|
||||
nonce_raw[8] = net_packet.protocol().into();
|
||||
nonce_raw[9] = net_packet.transport_protocol();
|
||||
nonce_raw[10] = net_packet.is_gateway() as u8;
|
||||
nonce_raw[11] = net_packet.source_ttl();
|
||||
let nonce = aead::Nonce::assume_unique_for_key(nonce_raw);
|
||||
let data_len = net_packet.data_len() + AES_GCM_ENCRYPTION_RESERVED;
|
||||
net_packet.set_data_len(data_len)?;
|
||||
let mut secret_body = SecretBody::new(net_packet.payload_mut(), self.finger.is_some())?;
|
||||
let rs = self.cipher.seal_in_place_separate_tag(
|
||||
nonce,
|
||||
aead::Aad::empty(),
|
||||
secret_body.body_mut(),
|
||||
);
|
||||
return match rs {
|
||||
Ok(tag) => {
|
||||
let tag = tag.as_ref();
|
||||
if tag.len() != 16 {
|
||||
return Err(anyhow!("加密tag长度错误:{}", tag.len()));
|
||||
}
|
||||
secret_body.set_tag(tag)?;
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body.en_body());
|
||||
secret_body.set_finger(&finger)?;
|
||||
}
|
||||
net_packet.set_encrypt_flag(true);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(anyhow!("ring CHACHA20_POLY1305 加密失败:{}", e)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ring_chacha20_poly1305() {
|
||||
let d = ChaCha20Poly1305Cipher::new_256([0; 32], Some(Finger::new("123")));
|
||||
let mut p = NetPacket::new_encrypt([0; 73]).unwrap();
|
||||
let src = p.buffer().to_vec();
|
||||
d.encrypt_ipv4(&mut p).unwrap();
|
||||
d.decrypt_ipv4(&mut p).unwrap();
|
||||
assert_eq!(p.buffer(), &src);
|
||||
let d = ChaCha20Poly1305Cipher::new_256([0; 32], None);
|
||||
let mut p = NetPacket::new_encrypt([0; 73]).unwrap();
|
||||
let src = p.buffer().to_vec();
|
||||
d.encrypt_ipv4(&mut p).unwrap();
|
||||
d.decrypt_ipv4(&mut p).unwrap();
|
||||
assert_eq!(p.buffer(), &src);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use anyhow::anyhow;
|
||||
use chacha20poly1305::aead::{Nonce, Tag};
|
||||
use chacha20poly1305::{AeadInPlace, ChaCha20Poly1305, Key, KeyInit};
|
||||
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::body::{SecretBody, AES_GCM_ENCRYPTION_RESERVED};
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ChaCha20Poly1305Cipher {
|
||||
key: Vec<u8>,
|
||||
pub(crate) cipher: ChaCha20Poly1305,
|
||||
pub(crate) finger: Option<Finger>,
|
||||
}
|
||||
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
pub fn new_256(key: [u8; 32], finger: Option<Finger>) -> Self {
|
||||
let key: &Key = &key.into();
|
||||
let cipher = ChaCha20Poly1305::new(key);
|
||||
Self {
|
||||
key: key.to_vec(),
|
||||
cipher,
|
||||
finger,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
pub fn key(&self) -> &[u8] {
|
||||
&self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl ChaCha20Poly1305Cipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
if net_packet.payload().len() < AES_GCM_ENCRYPTION_RESERVED {
|
||||
log::error!("数据异常,长度小于{}", AES_GCM_ENCRYPTION_RESERVED);
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
nonce_raw[4..8].copy_from_slice(&net_packet.destination().octets());
|
||||
nonce_raw[8] = net_packet.protocol().into();
|
||||
nonce_raw[9] = net_packet.transport_protocol();
|
||||
nonce_raw[10] = net_packet.is_gateway() as u8;
|
||||
nonce_raw[11] = net_packet.source_ttl();
|
||||
let mut secret_body = SecretBody::new(net_packet.payload_mut(), self.finger.is_some())?;
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body.en_body());
|
||||
if &finger != secret_body.finger() {
|
||||
return Err(anyhow!("rs CHACHA20_POLY1305 finger err"));
|
||||
}
|
||||
}
|
||||
let nonce: Nonce<ChaCha20Poly1305> = nonce_raw.into();
|
||||
let tag: Tag<ChaCha20Poly1305> =
|
||||
Tag::<ChaCha20Poly1305>::from_slice(secret_body.tag()).clone();
|
||||
if let Err(e) =
|
||||
self.cipher
|
||||
.decrypt_in_place_detached(&nonce, &[], secret_body.body_mut(), &tag)
|
||||
{
|
||||
return Err(anyhow!("rs CHACHA20_POLY1305 decrypt_ipv4 {:?}", e));
|
||||
}
|
||||
net_packet.set_encrypt_flag(false);
|
||||
net_packet.set_data_len(net_packet.data_len() - AES_GCM_ENCRYPTION_RESERVED)?;
|
||||
Ok(())
|
||||
}
|
||||
/// net_packet 必须预留足够长度
|
||||
/// data_len是有效载荷的长度
|
||||
/// 返回加密后载荷的长度
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
nonce_raw[4..8].copy_from_slice(&net_packet.destination().octets());
|
||||
nonce_raw[8] = net_packet.protocol().into();
|
||||
nonce_raw[9] = net_packet.transport_protocol();
|
||||
nonce_raw[10] = net_packet.is_gateway() as u8;
|
||||
nonce_raw[11] = net_packet.source_ttl();
|
||||
let nonce = nonce_raw.into();
|
||||
let data_len = net_packet.data_len() + AES_GCM_ENCRYPTION_RESERVED;
|
||||
net_packet.set_data_len(data_len)?;
|
||||
let mut secret_body = SecretBody::new(net_packet.payload_mut(), self.finger.is_some())?;
|
||||
let rs = self
|
||||
.cipher
|
||||
.encrypt_in_place_detached(&nonce, &[], secret_body.body_mut());
|
||||
return match rs {
|
||||
Ok(tag) => {
|
||||
let tag: &[u8] = tag.as_ref();
|
||||
if tag.len() != 16 {
|
||||
return Err(anyhow!("加密tag长度错误:{}", tag.len(),));
|
||||
}
|
||||
secret_body.set_tag(tag)?;
|
||||
if let Some(finger) = &self.finger {
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body.en_body());
|
||||
secret_body.set_finger(&finger)?;
|
||||
}
|
||||
net_packet.set_encrypt_flag(true);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(anyhow!("rs CHACHA20_POLY1305 加密失败:{}", e)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rs_chacha20_poly1305() {
|
||||
let d = ChaCha20Poly1305Cipher::new_256([0; 32], Some(Finger::new("123")));
|
||||
let mut p = NetPacket::new_encrypt([0; 73]).unwrap();
|
||||
let src = p.buffer().to_vec();
|
||||
d.encrypt_ipv4(&mut p).unwrap();
|
||||
d.decrypt_ipv4(&mut p).unwrap();
|
||||
assert_eq!(p.buffer(), &src);
|
||||
}
|
||||
+112
-132
@@ -1,110 +1,99 @@
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
#[cfg(not(any(feature = "openssl-vendored", feature = "openssl")))]
|
||||
use crate::cipher::aes_ecb::AesEcbCipher;
|
||||
use std::fmt::Display;
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::anyhow;
|
||||
#[cfg(cipher)]
|
||||
use sha2::Digest;
|
||||
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
use crate::cipher::aes_cbc::AesCbcCipher;
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
#[cfg(not(feature = "ring-cipher"))]
|
||||
use crate::cipher::aes_gcm_cipher::AesGcmCipher;
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
#[cfg(any(feature = "openssl-vendored", feature = "openssl"))]
|
||||
use crate::cipher::openssl_aes_ecb::AesEcbCipher;
|
||||
use crate::cipher::aes_ecb::AesEcbCipher;
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
#[cfg(feature = "ring-cipher")]
|
||||
use crate::cipher::ring_aes_gcm_cipher::AesGcmCipher;
|
||||
use crate::cipher::aes_gcm::AesGcmCipher;
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
use crate::cipher::chacha20::ChaCha20Cipher;
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
use crate::cipher::chacha20_poly1305::ChaCha20Poly1305Cipher;
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
use crate::cipher::sm4_cbc::Sm4CbcCipher;
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
use crate::cipher::xor::XORCipher;
|
||||
#[cfg(cipher)]
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::NetPacket;
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
use sha2::Digest;
|
||||
use std::io;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
|
||||
pub enum CipherModel {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
AesGcm,
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Chacha20Poly1305,
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Chacha20,
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
AesCbc,
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
AesEcb,
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
Sm4Cbc,
|
||||
Xor,
|
||||
None,
|
||||
}
|
||||
|
||||
impl Display for CipherModel {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let str = match self {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
CipherModel::AesGcm => "aes_gcm".to_string(),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
CipherModel::Chacha20Poly1305 => "chacha20_poly1305".to_string(),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
CipherModel::Chacha20 => "chacha20".to_string(),
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
CipherModel::AesCbc => "aes_cbc".to_string(),
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
CipherModel::AesEcb => "aes_ecb".to_string(),
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
CipherModel::Sm4Cbc => "sm4_cbc".to_string(),
|
||||
CipherModel::Xor => "xor".to_string(),
|
||||
CipherModel::None => "none".to_string(),
|
||||
};
|
||||
write!(f, "{}", str)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for CipherModel {
|
||||
type Err = String;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
#[cfg(not(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)))]
|
||||
return Err(format!("not match '{}', no encrypt", s));
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
match s.to_lowercase().trim() {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
"aes_gcm" => Ok(CipherModel::AesGcm),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
"chacha20_poly1305" => Ok(CipherModel::Chacha20Poly1305),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
"chacha20" => Ok(CipherModel::Chacha20),
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
"aes_cbc" => Ok(CipherModel::AesCbc),
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
"aes_ecb" => Ok(CipherModel::AesEcb),
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
"sm4_cbc" => Ok(CipherModel::Sm4Cbc),
|
||||
"xor" => Ok(CipherModel::Xor),
|
||||
_ => {
|
||||
let mut enums = String::new();
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
enums.push_str("/aes_gcm");
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
enums.push_str("/chacha20_poly1305/chacha20");
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
enums.push_str("/aes_cbc");
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
enums.push_str("/aes_ecb");
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
enums.push_str("/sm4_cbc");
|
||||
let str = if enums.is_empty() {
|
||||
"no encrypt"
|
||||
} else {
|
||||
&enums[1..]
|
||||
};
|
||||
Err(format!("not match '{}', enum:{}", s, str))
|
||||
enums.push_str("/xor");
|
||||
Err(format!("not match '{}', enum:{}", s, &enums[1..]))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,49 +103,37 @@ impl FromStr for CipherModel {
|
||||
pub enum Cipher {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
AesGcm((AesGcmCipher, Vec<u8>)),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Chacha20Poly1305(ChaCha20Poly1305Cipher),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Chacha20(ChaCha20Cipher),
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
AesCbc(AesCbcCipher),
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
AesEcb(AesEcbCipher),
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
Sm4Cbc(Sm4CbcCipher),
|
||||
Xor(XORCipher),
|
||||
None,
|
||||
}
|
||||
|
||||
impl Cipher {
|
||||
#[cfg(not(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)))]
|
||||
pub fn new_password(
|
||||
_model: CipherModel,
|
||||
_password: Option<String>,
|
||||
_token: Option<String>,
|
||||
) -> Self {
|
||||
Cipher::None
|
||||
}
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
pub fn new_password(
|
||||
model: CipherModel,
|
||||
password: Option<String>,
|
||||
token: Option<String>,
|
||||
) -> Self {
|
||||
let finger = token.map(|token| Finger::new(&token));
|
||||
if let Some(password) = password {
|
||||
let mut hasher = sha2::Sha256::new();
|
||||
hasher.update(password.as_bytes());
|
||||
let key: [u8; 32] = hasher.finalize().into();
|
||||
#[cfg(cipher)]
|
||||
let key: [u8; 32] = {
|
||||
let mut hasher = sha2::Sha256::new();
|
||||
hasher.update(password.as_bytes());
|
||||
hasher.finalize().into()
|
||||
};
|
||||
match model {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
CipherModel::AesGcm => {
|
||||
let finger = token.map(|token| Finger::new(&token));
|
||||
if password.len() < 8 {
|
||||
let aes = AesGcmCipher::new_128(key[..16].try_into().unwrap(), finger);
|
||||
Cipher::AesGcm((aes, key[..16].to_vec()))
|
||||
@@ -165,8 +142,21 @@ impl Cipher {
|
||||
Cipher::AesGcm((aes, key.to_vec()))
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
CipherModel::Chacha20Poly1305 => {
|
||||
let finger = token.map(|token| Finger::new(&token));
|
||||
let chacha = ChaCha20Poly1305Cipher::new_256(key, finger);
|
||||
Cipher::Chacha20Poly1305(chacha)
|
||||
}
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
CipherModel::Chacha20 => {
|
||||
let finger = token.map(|token| Finger::new(&token));
|
||||
let chacha = ChaCha20Cipher::new_256(key, finger);
|
||||
Cipher::Chacha20(chacha)
|
||||
}
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
CipherModel::AesCbc => {
|
||||
let finger = token.map(|token| Finger::new(&token));
|
||||
if password.len() < 8 {
|
||||
let aes = AesCbcCipher::new_128(key[..16].try_into().unwrap(), finger);
|
||||
Cipher::AesCbc(aes)
|
||||
@@ -177,6 +167,7 @@ impl Cipher {
|
||||
}
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
CipherModel::AesEcb => {
|
||||
let finger = token.map(|token| Finger::new(&token));
|
||||
if password.len() < 8 {
|
||||
let aes = AesEcbCipher::new_128(key[..16].try_into().unwrap(), finger);
|
||||
Cipher::AesEcb(aes)
|
||||
@@ -187,126 +178,97 @@ impl Cipher {
|
||||
}
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
CipherModel::Sm4Cbc => {
|
||||
let finger = token.map(|token| Finger::new(&token));
|
||||
let aes = Sm4CbcCipher::new_128(key[..16].try_into().unwrap(), finger);
|
||||
Cipher::Sm4Cbc(aes)
|
||||
}
|
||||
CipherModel::Xor => {
|
||||
let _token = token;
|
||||
Cipher::Xor(XORCipher::new_256(crate::cipher::xor::simple_hash(
|
||||
&password,
|
||||
)))
|
||||
}
|
||||
CipherModel::None => Cipher::None,
|
||||
}
|
||||
} else {
|
||||
Cipher::None
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)))]
|
||||
pub fn new_key(_key: [u8; 32], _token: String) -> io::Result<Self> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "key error"))
|
||||
#[cfg(not(any(feature = "aes_gcm", feature = "server_encrypt")))]
|
||||
pub fn new_key(_key: [u8; 32], _token: String) -> anyhow::Result<Self> {
|
||||
Err(anyhow!("key error"))
|
||||
}
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
pub fn new_key(key: [u8; 32], token: String) -> io::Result<Self> {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
pub fn new_key(key: [u8; 32], token: String) -> anyhow::Result<Self> {
|
||||
let finger = Some(Finger::new(&token));
|
||||
match key.len() {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
16 => {
|
||||
let aes = AesGcmCipher::new_128(key[..16].try_into().unwrap(), finger);
|
||||
Ok(Cipher::AesGcm((aes, key[..16].to_vec())))
|
||||
}
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
32 => {
|
||||
let aes = AesGcmCipher::new_256(key, finger);
|
||||
Ok(Cipher::AesGcm((aes, key.to_vec())))
|
||||
}
|
||||
_ => Err(io::Error::new(io::ErrorKind::Other, "key error")),
|
||||
_ => Err(anyhow!("key error")),
|
||||
}
|
||||
}
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
match self {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
Cipher::AesGcm((aes_gcm, _)) => aes_gcm.decrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
Cipher::AesCbc(aes_cbc) => aes_cbc.decrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20Poly1305(chacha20poly1305) => chacha20poly1305.decrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20(chacha20) => chacha20.decrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
Cipher::AesEcb(aes_ecb) => aes_ecb.decrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
Cipher::Sm4Cbc(sm4_cbc) => sm4_cbc.decrypt_ipv4(net_packet),
|
||||
Cipher::Xor(xor) => xor.decrypt_ipv4(net_packet),
|
||||
Cipher::None => {
|
||||
if net_packet.is_encrypt() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not key"));
|
||||
return Err(anyhow!("not key"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)))]
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
_net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
match self {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
Cipher::AesGcm((aes_gcm, _)) => aes_gcm.encrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20Poly1305(chacha20poly1305) => chacha20poly1305.encrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20(chacha20) => chacha20.encrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
Cipher::AesCbc(aes_cbc) => aes_cbc.encrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
Cipher::AesEcb(aes_ecb) => aes_ecb.encrypt_ipv4(net_packet),
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
Cipher::Sm4Cbc(sm4_cbc) => sm4_cbc.encrypt_ipv4(net_packet),
|
||||
Cipher::Xor(xor) => xor.encrypt_ipv4(net_packet),
|
||||
Cipher::None => Ok(()),
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
)))]
|
||||
#[cfg(not(cipher))]
|
||||
pub fn check_finger<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
_net_packet: &NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
pub fn check_finger<B: AsRef<[u8]>>(&self, net_packet: &NetPacket<B>) -> io::Result<()> {
|
||||
#[cfg(cipher)]
|
||||
pub fn check_finger<B: AsRef<[u8]>>(&self, net_packet: &NetPacket<B>) -> anyhow::Result<()> {
|
||||
match self {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
Cipher::AesGcm((aes_gcm, _)) => aes_gcm
|
||||
@@ -314,6 +276,18 @@ impl Cipher {
|
||||
.as_ref()
|
||||
.map(|f| f.check_finger(net_packet))
|
||||
.unwrap_or(Ok(())),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20Poly1305(chacha20poly1305) => chacha20poly1305
|
||||
.finger
|
||||
.as_ref()
|
||||
.map(|f| f.check_finger(net_packet))
|
||||
.unwrap_or(Ok(())),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20(chacha20) => chacha20
|
||||
.finger
|
||||
.as_ref()
|
||||
.map(|f| f.check_finger(net_packet))
|
||||
.unwrap_or(Ok(())),
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
Cipher::AesCbc(aes_cbc) => aes_cbc
|
||||
.finger
|
||||
@@ -332,6 +306,7 @@ impl Cipher {
|
||||
.as_ref()
|
||||
.map(|f| f.check_finger(net_packet))
|
||||
.unwrap_or(Ok(())),
|
||||
Cipher::Xor(_) => Ok(()),
|
||||
Cipher::None => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -339,12 +314,17 @@ impl Cipher {
|
||||
match self {
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
Cipher::AesGcm((_, key)) => Some(key),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20Poly1305(chacha20poly1305) => Some(chacha20poly1305.key()),
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
Cipher::Chacha20(chacha20) => Some(chacha20.key()),
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
Cipher::AesCbc(aes_cbc) => Some(aes_cbc.key()),
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
Cipher::AesEcb(aes_ecb) => Some(aes_ecb.key()),
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
Cipher::Sm4Cbc(sm4_cbc) => Some(sm4_cbc.key()),
|
||||
Cipher::Xor(xor) => Some(xor.key()),
|
||||
Cipher::None => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::io;
|
||||
use anyhow::anyhow;
|
||||
|
||||
use sha2::Digest;
|
||||
|
||||
@@ -16,15 +16,15 @@ impl Finger {
|
||||
let hash: [u8; 32] = hasher.finalize().into();
|
||||
Finger { hash }
|
||||
}
|
||||
pub fn check_finger<B: AsRef<[u8]>>(&self, net_packet: &NetPacket<B>) -> io::Result<()> {
|
||||
pub fn check_finger<B: AsRef<[u8]>>(&self, net_packet: &NetPacket<B>) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not encrypt"));
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
let payload_len = net_packet.payload().len();
|
||||
if payload_len < 12 {
|
||||
log::error!("数据异常,长度小于{}", 12);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let mut nonce_raw = [0; 12];
|
||||
nonce_raw[0..4].copy_from_slice(&net_packet.source().octets());
|
||||
@@ -36,7 +36,7 @@ impl Finger {
|
||||
let payload = net_packet.payload();
|
||||
let finger = self.calculate_finger(&nonce_raw, &payload[..payload_len - 12]);
|
||||
if &finger[..] != &payload[payload_len - 12..] {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "finger err"));
|
||||
return Err(anyhow!("finger err"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+22
-30
@@ -1,40 +1,32 @@
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
mod aes_cbc;
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
#[cfg(not(any(feature = "openssl-vendored", feature = "openssl")))]
|
||||
mod aes_ecb;
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
#[cfg(not(feature = "ring-cipher"))]
|
||||
mod aes_gcm_cipher;
|
||||
mod cipher;
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
#[cfg(cipher)]
|
||||
mod finger;
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
#[cfg(any(feature = "openssl-vendored", feature = "openssl"))]
|
||||
mod openssl_aes_ecb;
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
#[cfg(feature = "ring-cipher")]
|
||||
mod ring_aes_gcm_cipher;
|
||||
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
mod sm4_cbc;
|
||||
pub use cipher::Cipher;
|
||||
pub use cipher::CipherModel;
|
||||
#[cfg(any(
|
||||
feature = "aes_gcm",
|
||||
feature = "server_encrypt",
|
||||
feature = "aes_cbc",
|
||||
feature = "aes_ecb",
|
||||
feature = "sm4_cbc"
|
||||
))]
|
||||
#[cfg(cipher)]
|
||||
pub use finger::Finger;
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
mod rsa_cipher;
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
pub use rsa_cipher::RsaCipher;
|
||||
|
||||
#[cfg(any(feature = "aes_gcm", feature = "server_encrypt"))]
|
||||
mod aes_gcm;
|
||||
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
mod chacha20;
|
||||
#[cfg(feature = "chacha20_poly1305")]
|
||||
mod chacha20_poly1305;
|
||||
|
||||
#[cfg(feature = "aes_ecb")]
|
||||
mod aes_ecb;
|
||||
|
||||
#[cfg(feature = "aes_cbc")]
|
||||
mod aes_cbc;
|
||||
|
||||
#[cfg(feature = "sm4_cbc")]
|
||||
mod sm4_cbc;
|
||||
|
||||
mod xor;
|
||||
pub use xor::simple_hash;
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
mod rs_sm4_cbc;
|
||||
pub use rs_sm4_cbc::*;
|
||||
@@ -1,9 +1,9 @@
|
||||
use crate::cipher::Finger;
|
||||
use crate::protocol::{NetPacket, HEAD_LEN};
|
||||
use anyhow::anyhow;
|
||||
use libsm::sm4::cipher_mode::CipherMode;
|
||||
use libsm::sm4::Sm4CipherMode;
|
||||
use rand::RngCore;
|
||||
use std::io;
|
||||
|
||||
pub struct Sm4CbcCipher {
|
||||
key: [u8; 16],
|
||||
@@ -41,10 +41,10 @@ impl Sm4CbcCipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "not encrypt"));
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
|
||||
if let Some(finger) = &self.finger {
|
||||
@@ -57,12 +57,12 @@ impl Sm4CbcCipher {
|
||||
nonce_raw[11] = net_packet.source_ttl();
|
||||
let len = net_packet.payload().len();
|
||||
if len < 12 {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "payload len <12"));
|
||||
return Err(anyhow!("payload len <12"));
|
||||
}
|
||||
let secret_body = &net_packet.payload()[..len - 12];
|
||||
let finger = finger.calculate_finger(&nonce_raw, secret_body);
|
||||
if &finger != &net_packet.payload()[len - 12..] {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "finger err"));
|
||||
return Err(anyhow!("finger err"));
|
||||
}
|
||||
net_packet.set_data_len(net_packet.data_len() - finger.len())?;
|
||||
}
|
||||
@@ -70,7 +70,7 @@ impl Sm4CbcCipher {
|
||||
let len = payload.len();
|
||||
if len < 16 || len > 1024 * 4 {
|
||||
log::error!("数据异常,长度{}小于16或大于4096", len);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
let mut out = [0u8; 1024 * 4];
|
||||
let data = &payload[..len - 16];
|
||||
@@ -79,32 +79,29 @@ impl Sm4CbcCipher {
|
||||
Ok(len) => {
|
||||
let src_net_packet = NetPacket::new(&out[..len])?;
|
||||
if src_net_packet.source() != net_packet.source() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.destination() != net_packet.destination() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.protocol() != net_packet.protocol() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.transport_protocol() != net_packet.transport_protocol() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.is_gateway() != net_packet.is_gateway() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
if src_net_packet.source_ttl() != net_packet.source_ttl() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
net_packet.set_data_len(len)?;
|
||||
net_packet.set_payload(src_net_packet.payload())?;
|
||||
net_packet.set_encrypt_flag(false);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("sm4_cbc解密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("sm4_cbc解密失败:{}", e)),
|
||||
}
|
||||
}
|
||||
/// net_packet 必须预留足够长度
|
||||
@@ -112,7 +109,7 @@ impl Sm4CbcCipher {
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let mut out = [0u8; 1024 * 4];
|
||||
let mut iv = [0u8; 16];
|
||||
rand::thread_rng().fill_bytes(&mut iv);
|
||||
@@ -121,7 +118,7 @@ impl Sm4CbcCipher {
|
||||
"数据异常,长度{}大于1024 * 4 - 32",
|
||||
net_packet.buffer().len()
|
||||
);
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "data err"));
|
||||
return Err(anyhow!("data err"));
|
||||
}
|
||||
match self.cipher.encrypt(net_packet.buffer(), &iv, &mut out) {
|
||||
Ok(len) => {
|
||||
@@ -146,10 +143,7 @@ impl Sm4CbcCipher {
|
||||
net_packet.set_encrypt_flag(true);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("sm4_cbc加密失败:{}", e),
|
||||
)),
|
||||
Err(e) => Err(anyhow!("sm4_cbc加密失败:{}", e)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
mod xor;
|
||||
pub use xor::*;
|
||||
@@ -0,0 +1,84 @@
|
||||
use anyhow::anyhow;
|
||||
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
pub fn simple_hash(input: &str) -> [u8; 32] {
|
||||
let mut result = [0u8; 32];
|
||||
let bytes = input.as_bytes();
|
||||
for (index, v) in result.iter_mut().enumerate() {
|
||||
*v = bytes[index % bytes.len()];
|
||||
}
|
||||
|
||||
let mut state = 0u8;
|
||||
|
||||
for (i, &byte) in bytes.iter().enumerate() {
|
||||
let combined = byte.wrapping_add(state).rotate_left((i % 8) as u32);
|
||||
result[i % 32] ^= combined;
|
||||
state = state.wrapping_add(byte).rotate_left(3);
|
||||
}
|
||||
|
||||
for i in 0..32 {
|
||||
result[i] = result[i]
|
||||
.rotate_left((result[(i + 1) % 32] % 8) as u32)
|
||||
.wrapping_add(state);
|
||||
state = state.wrapping_add(result[i]).rotate_left(3);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct XORCipher {
|
||||
key: [u8; 32],
|
||||
}
|
||||
|
||||
impl XORCipher {
|
||||
pub fn new_256(key: [u8; 32]) -> Self {
|
||||
Self { key }
|
||||
}
|
||||
}
|
||||
|
||||
impl XORCipher {
|
||||
pub fn key(&self) -> &[u8] {
|
||||
&self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl XORCipher {
|
||||
pub fn decrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
if !net_packet.is_encrypt() {
|
||||
//未加密的数据直接丢弃
|
||||
return Err(anyhow!("not encrypt"));
|
||||
}
|
||||
let key = &self.key;
|
||||
for (i, byte) in net_packet.payload_mut().iter_mut().enumerate() {
|
||||
*byte ^= key[i & 31];
|
||||
}
|
||||
net_packet.set_encrypt_flag(false);
|
||||
Ok(())
|
||||
}
|
||||
pub fn encrypt_ipv4<B: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
net_packet: &mut NetPacket<B>,
|
||||
) -> anyhow::Result<()> {
|
||||
net_packet.set_encrypt_flag(true);
|
||||
let key = &self.key;
|
||||
for (i, byte) in net_packet.payload_mut().iter_mut().enumerate() {
|
||||
*byte ^= key[i & 31];
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_xor() {
|
||||
let d = XORCipher::new_256(simple_hash("password"));
|
||||
let mut p = NetPacket::new_encrypt([0; 1000]).unwrap();
|
||||
let src = p.buffer().to_vec();
|
||||
d.encrypt_ipv4(&mut p).unwrap();
|
||||
d.decrypt_ipv4(&mut p).unwrap();
|
||||
assert_eq!(p.buffer(), &src)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use anyhow::anyhow;
|
||||
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Lz4Compressor;
|
||||
|
||||
impl Lz4Compressor {
|
||||
pub fn compress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
in_net_packet: &NetPacket<I>,
|
||||
out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<()> {
|
||||
out.set_data_len_max();
|
||||
let len = match lz4_flex::compress_into(in_net_packet.payload(), out.payload_mut()) {
|
||||
Ok(len) => len,
|
||||
Err(e) => Err(anyhow!("Lz4 compress {}", e))?,
|
||||
};
|
||||
out.set_payload_len(len)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn decompress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
in_net_packet: &NetPacket<I>,
|
||||
out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<()> {
|
||||
out.set_data_len_max();
|
||||
let len = match lz4_flex::decompress_into(in_net_packet.payload(), out.payload_mut()) {
|
||||
Ok(len) => len,
|
||||
Err(e) => Err(anyhow!("Lz4 decompress {}", e))?,
|
||||
};
|
||||
out.set_payload_len(len)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::anyhow;
|
||||
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
use crate::compression::lz4_compress::Lz4Compressor;
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
use crate::compression::zstd_compress::ZstdCompressor;
|
||||
use crate::protocol::extension::CompressionAlgorithm;
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
use zstd::zstd_safe::CompressionLevel;
|
||||
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
mod lz4_compress;
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
mod zstd_compress;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Compressor {
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
Lz4,
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
Zstd(CompressionLevel),
|
||||
None,
|
||||
}
|
||||
|
||||
impl FromStr for Compressor {
|
||||
type Err = String;
|
||||
#[cfg(not(any(feature = "lz4_compress", feature = "zstd_compress")))]
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
Err(format!("not match '{}', Compression not supported", s))
|
||||
}
|
||||
#[cfg(any(feature = "lz4_compress", feature = "zstd_compress"))]
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let str = s.trim().to_lowercase();
|
||||
match str.as_str() {
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
"lz4" => Ok(Compressor::Lz4),
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
"zstd" => Ok(Compressor::Zstd(9)),
|
||||
"none" => Ok(Compressor::None),
|
||||
_ => {
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
{
|
||||
let string_array: Vec<String> = str.split(',').map(|s| s.to_string()).collect();
|
||||
if string_array.len() != 2 || string_array[0] != "zstd" {
|
||||
return Err(format!("not match '{}', exp: zstd,10", s));
|
||||
}
|
||||
return match CompressionLevel::from_str(&string_array[1]) {
|
||||
Ok(level) => Ok(Compressor::Zstd(level)),
|
||||
Err(_) => Err(format!("not match '{}', exp: zstd,10", s)),
|
||||
};
|
||||
}
|
||||
#[cfg(not(feature = "zstd_compress"))]
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
return Err(format!("not match '{}', exp: lz4", s));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(any(feature = "lz4_compress", feature = "zstd_compress")))]
|
||||
impl Compressor {
|
||||
pub fn compress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
_in_net_packet: &NetPacket<I>,
|
||||
_out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<bool> {
|
||||
Ok(false)
|
||||
}
|
||||
pub fn decompress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
_algorithm: CompressionAlgorithm,
|
||||
_in_net_packet: &NetPacket<I>,
|
||||
_out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<()> {
|
||||
Err(anyhow!("Unsupported decompress"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "lz4_compress", feature = "zstd_compress"))]
|
||||
impl Compressor {
|
||||
pub fn compress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
&self,
|
||||
in_net_packet: &NetPacket<I>,
|
||||
out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<bool> {
|
||||
match self {
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
Compressor::Lz4 => {
|
||||
if in_net_packet.data_len() < 128 {
|
||||
return Ok(false);
|
||||
}
|
||||
Lz4Compressor::compress(in_net_packet, out)?;
|
||||
let mut compression_extension_tail = out.append_compression_extension_tail()?;
|
||||
compression_extension_tail.set_algorithm(CompressionAlgorithm::Lz4);
|
||||
//压缩没效果,则放弃压缩
|
||||
if out.data_len() >= in_net_packet.data_len() - 16 {
|
||||
return Ok(false);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
Compressor::Zstd(level) => {
|
||||
if in_net_packet.data_len() < 128 {
|
||||
return Ok(false);
|
||||
}
|
||||
ZstdCompressor::compress(*level, in_net_packet, out)?;
|
||||
let mut compression_extension_tail = out.append_compression_extension_tail()?;
|
||||
compression_extension_tail.set_algorithm(CompressionAlgorithm::Zstd);
|
||||
//压缩没效果,则放弃压缩
|
||||
if out.data_len() >= in_net_packet.data_len() - 16 {
|
||||
return Ok(false);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
Compressor::None => {}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
pub fn decompress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
algorithm: CompressionAlgorithm,
|
||||
in_net_packet: &NetPacket<I>,
|
||||
out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<()> {
|
||||
match algorithm {
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
CompressionAlgorithm::Lz4 => Lz4Compressor::decompress(in_net_packet, out),
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
CompressionAlgorithm::Zstd => ZstdCompressor::decompress(in_net_packet, out),
|
||||
_ => Err(anyhow!("Unknown decompress {:?}", algorithm)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lz4() {
|
||||
use crate::protocol::extension::{CompressionAlgorithm, ExtensionTailPacket};
|
||||
let lz4 = Compressor::Lz4;
|
||||
let in_packet = NetPacket::new([
|
||||
65, 108, 105, 99, 101, 32, 119, 97, 116, 32, 98, 101, 103, 105, 110, 110, 105, 110, 103,
|
||||
32, 116, 111, 32, 103, 101, 116, 32, 118, 101, 114, 121, 32, 116, 105, 114, 101, 100, 32,
|
||||
111, 102, 32, 115, 105, 116, 116, 105, 110, 103, 32, 98, 121, 32, 104, 101, 114, 32, 115,
|
||||
105, 115, 116, 101, 114, 32, 111, 110, 32, 116, 104, 101, 32, 98, 97, 110, 107, 44, 32, 97,
|
||||
110, 100, 32, 111, 102, 32, 104, 97, 118, 105, 110, 103, 32, 110, 111, 116, 104, 105, 110,
|
||||
103, 32, 116, 111, 32, 100, 111, 58, 32, 111, 110, 99, 101, 32, 111, 114, 32, 116, 119,
|
||||
105, 99, 101, 32, 115, 104, 101, 32, 104, 97, 100, 32, 112, 101, 101, 112, 101, 100, 32,
|
||||
105, 110, 116, 111, 32, 116, 104, 101, 32, 98, 111, 111, 107, 32, 104, 101, 114, 32, 115,
|
||||
105, 115, 116, 101, 114, 32, 119, 97, 115, 32, 114, 101, 97, 100, 105, 110, 103, 44, 32,
|
||||
98, 117, 116, 32, 105, 116, 32, 104, 97, 100, 32, 110, 111, 32, 112, 105, 99, 116, 117,
|
||||
114, 101, 115, 32, 111, 114, 32, 99, 111, 110, 118, 101, 114, 115, 97, 116, 105,
|
||||
])
|
||||
.unwrap();
|
||||
let mut out_packet = NetPacket::new([0; 1000]).unwrap();
|
||||
let mut src_out_packet = NetPacket::new([0; 1000]).unwrap();
|
||||
lz4.compress(&in_packet, &mut out_packet).unwrap();
|
||||
let tail = out_packet.split_tail_packet().unwrap();
|
||||
match tail {
|
||||
ExtensionTailPacket::Compression(c) => match c.algorithm() {
|
||||
CompressionAlgorithm::Lz4 => {
|
||||
Compressor::decompress(CompressionAlgorithm::Lz4, &out_packet, &mut src_out_packet)
|
||||
.unwrap();
|
||||
}
|
||||
_ => {
|
||||
unimplemented!()
|
||||
}
|
||||
},
|
||||
ExtensionTailPacket::Unknown => {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
assert!(!out_packet.is_extension());
|
||||
assert_eq!(in_packet.payload(), src_out_packet.payload())
|
||||
}
|
||||
#[test]
|
||||
fn test_zstd() {
|
||||
use crate::protocol::extension::{CompressionAlgorithm, ExtensionTailPacket};
|
||||
let zstd = Compressor::Zstd(22);
|
||||
let in_packet = NetPacket::new([
|
||||
65, 108, 105, 99, 101, 32, 119, 97, 115, 32, 98, 101, 103, 105, 110, 110, 105, 110, 103,
|
||||
32, 116, 111, 32, 103, 101, 116, 32, 118, 101, 114, 121, 32, 116, 105, 114, 101, 100, 32,
|
||||
111, 102, 32, 115, 105, 116, 116, 105, 110, 103, 32, 98, 121, 32, 104, 101, 114, 32, 115,
|
||||
105, 115, 116, 101, 114, 32, 111, 110, 32, 116, 104, 101, 32, 98, 97, 110, 107, 44, 32, 97,
|
||||
110, 100, 32, 111, 102, 32, 104, 97, 118, 105, 110, 103, 32, 110, 111, 116, 104, 105, 110,
|
||||
103, 32, 116, 111, 32, 100, 111, 58, 32, 111, 110, 99, 101, 32, 111, 114, 32, 116, 119,
|
||||
105, 99, 101, 32, 115, 104, 101, 32, 104, 97, 100, 32, 112, 101, 101, 112, 101, 100, 32,
|
||||
105, 110, 116, 111, 32, 116, 104, 101, 32, 98, 111, 111, 107, 32, 104, 101, 114, 32, 115,
|
||||
105, 115, 116, 101, 114, 32, 119, 97, 115, 32, 114, 101, 97, 100, 105, 110, 103, 44, 32,
|
||||
98, 117, 116, 32, 105, 116, 32, 104, 97, 100, 32, 110, 111, 32, 112, 105, 99, 116, 117,
|
||||
114, 101, 115, 32, 111, 114, 32, 99, 111, 110, 118, 101, 114, 115, 97, 116, 105,
|
||||
])
|
||||
.unwrap();
|
||||
let mut out_packet = NetPacket::new([0; 1000]).unwrap();
|
||||
let mut src_out_packet = NetPacket::new([0; 1000]).unwrap();
|
||||
zstd.compress(&in_packet, &mut out_packet).unwrap();
|
||||
let tail = out_packet.split_tail_packet().unwrap();
|
||||
match tail {
|
||||
ExtensionTailPacket::Compression(c) => match c.algorithm() {
|
||||
CompressionAlgorithm::Zstd => {
|
||||
Compressor::decompress(
|
||||
CompressionAlgorithm::Zstd,
|
||||
&out_packet,
|
||||
&mut src_out_packet,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
_ => {
|
||||
unimplemented!()
|
||||
}
|
||||
},
|
||||
ExtensionTailPacket::Unknown => {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
assert!(!out_packet.is_extension());
|
||||
assert_eq!(in_packet.payload(), src_out_packet.payload())
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
use crate::protocol::NetPacket;
|
||||
use anyhow::anyhow;
|
||||
use zstd::zstd_safe::CompressionLevel;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ZstdCompressor;
|
||||
|
||||
impl ZstdCompressor {
|
||||
pub fn compress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
compression_level: CompressionLevel,
|
||||
in_net_packet: &NetPacket<I>,
|
||||
out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<()> {
|
||||
out.set_data_len_max();
|
||||
let len = match zstd::zstd_safe::compress(
|
||||
out.payload_mut(),
|
||||
in_net_packet.payload(),
|
||||
compression_level,
|
||||
) {
|
||||
Ok(len) => len,
|
||||
Err(e) => Err(anyhow!("zstd compress {}", e))?,
|
||||
};
|
||||
out.set_payload_len(len)?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn decompress<I: AsRef<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
in_net_packet: &NetPacket<I>,
|
||||
out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<()> {
|
||||
out.set_data_len_max();
|
||||
let len = match zstd::zstd_safe::decompress(out.payload_mut(), in_net_packet.payload()) {
|
||||
Ok(len) => len,
|
||||
Err(e) => Err(anyhow!("zstd decompress {}", e))?,
|
||||
};
|
||||
out.set_payload_len(len)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+57
-33
@@ -1,5 +1,4 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -7,7 +6,6 @@ use std::time::Duration;
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use rand::Rng;
|
||||
use rsa::signature::digest::Digest;
|
||||
#[cfg(not(target_os = "android"))]
|
||||
use tun::device::IFace;
|
||||
|
||||
@@ -40,7 +38,7 @@ pub struct Vnt {
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
nat_test: NatTest,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
context: ChannelContext,
|
||||
context: Arc<Mutex<Option<ChannelContext>>>,
|
||||
peer_nat_info_map: Arc<RwLock<HashMap<Ipv4Addr, NatInfo>>>,
|
||||
down_count_watcher: WatchU64Adder,
|
||||
up_count_watcher: WatchSingleU64Adder,
|
||||
@@ -48,8 +46,8 @@ pub struct Vnt {
|
||||
}
|
||||
|
||||
impl Vnt {
|
||||
pub fn new<Call: VntCallback>(config: Config, callback: Call) -> io::Result<Self> {
|
||||
log::info!("config:{:?}", config);
|
||||
pub fn new<Call: VntCallback>(config: Config, callback: Call) -> anyhow::Result<Self> {
|
||||
log::info!("config.toml:{:?}", config);
|
||||
//服务端非对称加密
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
let rsa_cipher: Arc<Mutex<Option<RsaCipher>>> = Arc::new(Mutex::new(None));
|
||||
@@ -81,26 +79,33 @@ impl Vnt {
|
||||
config.name.clone(),
|
||||
config.token.clone(),
|
||||
config.ip,
|
||||
config.password.as_ref().map(|v| {
|
||||
let mut hasher = sha2::Sha256::new();
|
||||
hasher.update(config.cipher_model.to_string().as_bytes());
|
||||
hasher.update(v.as_bytes());
|
||||
hasher.update(config.token.as_bytes());
|
||||
let key: [u8; 32] = hasher.finalize().into();
|
||||
key[16..].try_into().unwrap()
|
||||
}),
|
||||
config.password_hash(),
|
||||
config.server_encrypt,
|
||||
config.device_id.clone(),
|
||||
config.server_address_str.clone(),
|
||||
config.name_servers.clone(),
|
||||
);
|
||||
let ports = config.ports.as_ref().map_or(vec![0, 0], |v| {
|
||||
// 服务停止管理器
|
||||
let stop_manager = {
|
||||
let callback = callback.clone();
|
||||
StopManager::new(move || callback.stop())
|
||||
};
|
||||
#[cfg(feature = "port_mapping")]
|
||||
crate::port_mapping::start_port_mapping(
|
||||
stop_manager.clone(),
|
||||
config.port_mapping_list.clone(),
|
||||
)?;
|
||||
let mut ports = config.ports.as_ref().map_or(vec![0, 0], |v| {
|
||||
if v.is_empty() {
|
||||
vec![0, 0]
|
||||
} else {
|
||||
v.clone()
|
||||
}
|
||||
});
|
||||
if config.use_channel_type.is_only_relay() {
|
||||
//中继模式下只监听一个端口就够了
|
||||
ports.truncate(1);
|
||||
}
|
||||
//通道上下文
|
||||
let (context, tcp_listener) = init_context(
|
||||
ports,
|
||||
@@ -127,16 +132,14 @@ impl Vnt {
|
||||
// pc上先创建虚拟网卡
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
let device = {
|
||||
log::info!("开始创建tun");
|
||||
let device = tun_tap_device::create_device(&config)?;
|
||||
log::info!("创建tun成功");
|
||||
let tun_info = DeviceInfo::new(device.name()?, device.version()?);
|
||||
log::info!("tun信息{:?}", tun_info);
|
||||
callback.create_tun(tun_info);
|
||||
device
|
||||
};
|
||||
// 服务停止管理器
|
||||
let stop_manager = {
|
||||
let callback = callback.clone();
|
||||
StopManager::new(move || callback.stop())
|
||||
};
|
||||
// 定时器
|
||||
let scheduler = Scheduler::new(stop_manager.clone())?;
|
||||
let external_route = ExternalRoute::new(config.in_ips.clone());
|
||||
@@ -146,7 +149,6 @@ impl Vnt {
|
||||
let proxy_map = if !config.out_ips.is_empty() && !config.no_proxy {
|
||||
Some(crate::ip_proxy::init_proxy(
|
||||
context.clone(),
|
||||
scheduler.clone(),
|
||||
stop_manager.clone(),
|
||||
current_device.clone(),
|
||||
client_cipher.clone(),
|
||||
@@ -160,7 +162,10 @@ impl Vnt {
|
||||
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(rsa_cipher.clone());
|
||||
let handshake = Handshake::new(
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
rsa_cipher.clone(),
|
||||
);
|
||||
let up_counter = SingleU64Adder::new();
|
||||
let up_count_watcher = up_counter.watch();
|
||||
let tun_helper = TunDeviceHelper::new(
|
||||
@@ -175,6 +180,7 @@ impl Vnt {
|
||||
config.parallel,
|
||||
up_counter,
|
||||
device_list.clone(),
|
||||
config.compressor,
|
||||
);
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
let device_adapter = DeviceAdapter::new(device.clone());
|
||||
@@ -271,7 +277,7 @@ impl Vnt {
|
||||
current_device,
|
||||
nat_test,
|
||||
device_list,
|
||||
context,
|
||||
context: Arc::new(Mutex::new(Some(context))),
|
||||
peer_nat_info_map,
|
||||
down_count_watcher,
|
||||
up_count_watcher,
|
||||
@@ -324,15 +330,17 @@ pub fn start<Call: VntCallback>(
|
||||
client_cipher.clone(),
|
||||
);
|
||||
}
|
||||
// 定时地址探测
|
||||
maintain::addr_request(
|
||||
&scheduler,
|
||||
context.clone(),
|
||||
current_device.clone(),
|
||||
server_cipher.clone(),
|
||||
config_info.clone(),
|
||||
);
|
||||
|
||||
if !context.use_channel_type().is_only_relay() {
|
||||
// 定时地址探测
|
||||
maintain::addr_request(
|
||||
&scheduler,
|
||||
context.clone(),
|
||||
current_device.clone(),
|
||||
server_cipher.clone(),
|
||||
nat_test.clone(),
|
||||
config_info.clone(),
|
||||
);
|
||||
// 定时打洞
|
||||
maintain::punch(
|
||||
&scheduler,
|
||||
@@ -386,16 +394,24 @@ impl Vnt {
|
||||
device_list
|
||||
}
|
||||
pub fn route(&self, ip: &Ipv4Addr) -> Option<Route> {
|
||||
self.context.route_table.route_one(ip)
|
||||
self.context.lock().as_ref()?.route_table.route_one(ip)
|
||||
}
|
||||
pub fn is_gateway(&self, ip: &Ipv4Addr) -> bool {
|
||||
self.current_device.load().is_gateway(ip)
|
||||
}
|
||||
pub fn route_key(&self, route_key: &RouteKey) -> Option<Ipv4Addr> {
|
||||
self.context.route_table.route_to_id(route_key)
|
||||
self.context
|
||||
.lock()
|
||||
.as_ref()?
|
||||
.route_table
|
||||
.route_to_id(route_key)
|
||||
}
|
||||
pub fn route_table(&self) -> Vec<(Ipv4Addr, Vec<Route>)> {
|
||||
self.context.route_table.route_table()
|
||||
if let Some(context) = self.context.lock().as_ref() {
|
||||
context.route_table.route_table()
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
pub fn up_stream(&self) -> u64 {
|
||||
self.up_count_watcher.get()
|
||||
@@ -404,9 +420,17 @@ impl Vnt {
|
||||
self.down_count_watcher.get()
|
||||
}
|
||||
pub fn stop(&self) {
|
||||
//退出协助回收资源
|
||||
let _ = self.context.lock().take();
|
||||
self.stop_manager.stop()
|
||||
}
|
||||
pub fn wait(&self) {
|
||||
self.stop_manager.wait()
|
||||
}
|
||||
pub fn wait_timeout(&self, dur: Duration) -> bool {
|
||||
self.stop_manager.wait_timeout(dur)
|
||||
}
|
||||
pub fn config(&self) -> &Config {
|
||||
&self.config
|
||||
}
|
||||
}
|
||||
|
||||
+48
-4
@@ -7,13 +7,14 @@ pub use conn::Vnt;
|
||||
use crate::channel::punch::PunchModel;
|
||||
use crate::channel::UseChannelType;
|
||||
use crate::cipher::CipherModel;
|
||||
use crate::compression::Compressor;
|
||||
use crate::util::{address_choose, dns_query_all};
|
||||
|
||||
mod conn;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
pub tap: bool,
|
||||
pub token: String,
|
||||
pub device_id: String,
|
||||
@@ -43,18 +44,22 @@ pub struct Config {
|
||||
//控制丢包率
|
||||
pub packet_loss_rate: Option<f64>,
|
||||
pub packet_delay: u32,
|
||||
// 端口映射
|
||||
#[cfg(feature = "port_mapping")]
|
||||
pub port_mapping_list: Vec<(bool, SocketAddr, String)>,
|
||||
pub compressor: Compressor,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn new(
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))] tap: bool,
|
||||
#[cfg(target_os = "windows")] tap: bool,
|
||||
token: String,
|
||||
device_id: String,
|
||||
name: String,
|
||||
server_address_str: String,
|
||||
mut name_servers: Vec<String>,
|
||||
mut stun_server: Vec<String>,
|
||||
in_ips: Vec<(u32, u32, Ipv4Addr)>,
|
||||
mut in_ips: Vec<(u32, u32, Ipv4Addr)>,
|
||||
out_ips: Vec<(u32, u32)>,
|
||||
password: Option<String>,
|
||||
mtu: Option<u32>,
|
||||
@@ -72,6 +77,9 @@ impl Config {
|
||||
use_channel_type: UseChannelType,
|
||||
packet_loss_rate: Option<f64>,
|
||||
packet_delay: u32,
|
||||
// 例如 [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,
|
||||
) -> anyhow::Result<Self> {
|
||||
for x in stun_server.iter_mut() {
|
||||
if !x.contains(":") {
|
||||
@@ -96,8 +104,15 @@ impl Config {
|
||||
}
|
||||
let server_address =
|
||||
address_choose(dns_query_all(&server_address_str, name_servers.clone())?)?;
|
||||
#[cfg(feature = "port_mapping")]
|
||||
let port_mapping_list = crate::port_mapping::convert(port_mapping_list)?;
|
||||
|
||||
for (dest, mask, _) in &mut in_ips {
|
||||
*dest = *mask & *dest;
|
||||
}
|
||||
in_ips.sort_by(|(dest1, _, _), (dest2, _, _)| dest2.cmp(dest1));
|
||||
Ok(Self {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
tap,
|
||||
token,
|
||||
device_id,
|
||||
@@ -126,6 +141,35 @@ impl Config {
|
||||
use_channel_type,
|
||||
packet_loss_rate,
|
||||
packet_delay,
|
||||
#[cfg(feature = "port_mapping")]
|
||||
port_mapping_list,
|
||||
compressor,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn password_hash(&self) -> Option<[u8; 16]> {
|
||||
if let Some(p) = self.password.as_ref() {
|
||||
match self.cipher_model {
|
||||
CipherModel::Xor => {
|
||||
let key = crate::cipher::simple_hash(&format!("Xor{}{}", p, self.token));
|
||||
Some(key[16..].try_into().unwrap())
|
||||
}
|
||||
CipherModel::None => None,
|
||||
#[cfg(cipher)]
|
||||
_ => {
|
||||
use sha2::Digest;
|
||||
let mut hasher = sha2::Sha256::new();
|
||||
hasher.update(self.cipher_model.to_string().as_bytes());
|
||||
hasher.update(p.as_bytes());
|
||||
hasher.update(self.token.as_bytes());
|
||||
let key: [u8; 32] = hasher.finalize().into();
|
||||
Some(key[16..].try_into().unwrap())
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
|
||||
// 目标ip,子网掩码,网关
|
||||
|
||||
// 目标网段,子网掩码,网关
|
||||
#[derive(Clone)]
|
||||
pub struct ExternalRoute {
|
||||
route_table: Vec<(u32, u32, Ipv4Addr)>,
|
||||
}
|
||||
|
||||
impl ExternalRoute {
|
||||
pub fn new(route_table: Vec<(u32, u32, Ipv4Addr)>) -> Self {
|
||||
pub fn new(mut route_table: Vec<(u32, u32, Ipv4Addr)>) -> Self {
|
||||
for (dest, mask, _) in &mut route_table {
|
||||
*dest = *mask & *dest;
|
||||
}
|
||||
route_table.sort_by(|(dest1, _, _), (dest2, _, _)| dest2.cmp(dest1));
|
||||
Self { route_table }
|
||||
}
|
||||
pub fn route(&self, ip: &Ipv4Addr) -> Option<Ipv4Addr> {
|
||||
@@ -18,7 +21,7 @@ impl ExternalRoute {
|
||||
}
|
||||
let ip = u32::from_be_bytes(ip.octets());
|
||||
for (dest, mask, gateway) in self.route_table.iter() {
|
||||
if *mask & ip == *mask & *dest {
|
||||
if *mask & ip == *dest {
|
||||
return Some(*gateway);
|
||||
}
|
||||
}
|
||||
@@ -27,18 +30,23 @@ impl ExternalRoute {
|
||||
pub fn to_route(&self) -> Vec<(Ipv4Addr, Ipv4Addr)> {
|
||||
self.route_table
|
||||
.iter()
|
||||
.map(|(dest, mask, _)| (Ipv4Addr::from(*dest & *mask), Ipv4Addr::from(*mask)))
|
||||
.map(|(dest, mask, _)| (Ipv4Addr::from(*dest), Ipv4Addr::from(*mask)))
|
||||
.collect::<Vec<(Ipv4Addr, Ipv4Addr)>>()
|
||||
}
|
||||
}
|
||||
|
||||
// 目标网段,子网掩码
|
||||
#[derive(Clone)]
|
||||
pub struct AllowExternalRoute {
|
||||
route_table: Arc<Vec<(u32, u32)>>,
|
||||
}
|
||||
|
||||
impl AllowExternalRoute {
|
||||
pub fn new(route_table: Vec<(u32, u32)>) -> Self {
|
||||
pub fn new(mut route_table: Vec<(u32, u32)>) -> Self {
|
||||
for (dest, mask) in &mut route_table {
|
||||
*dest = *mask & *dest;
|
||||
}
|
||||
route_table.sort_by(|(dest1, _), (dest2, _)| dest2.cmp(dest1));
|
||||
Self {
|
||||
route_table: Arc::new(route_table),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
use crate::compression::Compressor;
|
||||
use crate::protocol::extension::ExtensionTailPacket;
|
||||
use crate::protocol::NetPacket;
|
||||
use anyhow::anyhow;
|
||||
|
||||
pub fn handle_extension_tail<I: AsRef<[u8]> + AsMut<[u8]>, O: AsRef<[u8]> + AsMut<[u8]>>(
|
||||
in_net_packet: &mut NetPacket<I>,
|
||||
out: &mut NetPacket<O>,
|
||||
) -> anyhow::Result<bool> {
|
||||
if in_net_packet.is_extension() {
|
||||
let tail_packet = in_net_packet.split_tail_packet()?;
|
||||
match tail_packet {
|
||||
ExtensionTailPacket::Compression(extension) => {
|
||||
let compression_algorithm = extension.algorithm();
|
||||
Compressor::decompress(compression_algorithm, &in_net_packet, out)?;
|
||||
out.head_mut().copy_from_slice(in_net_packet.head());
|
||||
Ok(true)
|
||||
}
|
||||
ExtensionTailPacket::Unknown => Err(anyhow!("Unknown decompress")),
|
||||
}
|
||||
} else {
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
use parking_lot::Mutex;
|
||||
use protobuf::Message;
|
||||
|
||||
@@ -28,12 +29,16 @@ pub enum HandshakeEnum {
|
||||
#[derive(Clone)]
|
||||
pub struct Handshake {
|
||||
time: Arc<AtomicCell<Instant>>,
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
rsa_cipher: Arc<Mutex<Option<RsaCipher>>>,
|
||||
}
|
||||
impl Handshake {
|
||||
pub fn new(rsa_cipher: Arc<Mutex<Option<RsaCipher>>>) -> Self {
|
||||
pub fn new(
|
||||
#[cfg(feature = "server_encrypt")] rsa_cipher: Arc<Mutex<Option<RsaCipher>>>,
|
||||
) -> Self {
|
||||
Handshake {
|
||||
time: Arc::new(AtomicCell::new(Instant::now() - Duration::from_secs(60))),
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
rsa_cipher,
|
||||
}
|
||||
}
|
||||
@@ -54,6 +59,7 @@ impl Handshake {
|
||||
let mut request = HandshakeRequest::new();
|
||||
request.secret = secret;
|
||||
request.version = crate::VNT_VERSION.to_string();
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
if let Some(finger) = self.rsa_cipher.lock().as_ref().map(|v| v.finger().clone()) {
|
||||
request.key_finger = finger;
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ use std::time::Duration;
|
||||
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;
|
||||
@@ -15,6 +17,7 @@ pub fn addr_request(
|
||||
context: ChannelContext,
|
||||
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
server_cipher: Cipher,
|
||||
nat_test: NatTest,
|
||||
_config: BaseConfigInfo,
|
||||
) {
|
||||
pub_address_request(
|
||||
@@ -22,31 +25,67 @@ pub fn addr_request(
|
||||
context,
|
||||
current_device_info.clone(),
|
||||
server_cipher,
|
||||
nat_test,
|
||||
0,
|
||||
);
|
||||
}
|
||||
pub fn pub_address_request(
|
||||
|
||||
fn pub_address_request(
|
||||
scheduler: &Scheduler,
|
||||
context: ChannelContext,
|
||||
current_device_info: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
server_cipher: Cipher,
|
||||
nat_test: NatTest,
|
||||
count: usize,
|
||||
) {
|
||||
addr_request0(&context, ¤t_device_info, &server_cipher);
|
||||
// 9秒发送一次
|
||||
let rs = scheduler.timeout(Duration::from_secs(9), |s| {
|
||||
pub_address_request(s, context, current_device_info, server_cipher)
|
||||
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,
|
||||
¤t_device_info,
|
||||
&server_cipher,
|
||||
&nat_test,
|
||||
index,
|
||||
) {
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
let nat_info = nat_test.nat_info();
|
||||
if nat_info.nat_type == NatType::Symmetric {
|
||||
//对称网络探测端口没啥作用,把频率放低,(锥形网络也只在打洞前需要探测端口,后续可以改改)
|
||||
if !nat_info.public_ports.contains(&0) && !nat_info.public_ips.is_empty() {
|
||||
time = 600;
|
||||
}
|
||||
}
|
||||
|
||||
let rs = scheduler.timeout(Duration::from_secs(time), move |s| {
|
||||
pub_address_request(
|
||||
s,
|
||||
context,
|
||||
current_device_info,
|
||||
server_cipher,
|
||||
nat_test,
|
||||
index + 1,
|
||||
)
|
||||
});
|
||||
if !rs {
|
||||
log::info!("定时任务停止");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn addr_request0(
|
||||
fn addr_request0(
|
||||
context: &ChannelContext,
|
||||
current_device: &AtomicCell<CurrentDeviceInfo>,
|
||||
server_cipher: &Cipher,
|
||||
) {
|
||||
nat_test: &NatTest,
|
||||
index: usize,
|
||||
) -> anyhow::Result<()> {
|
||||
let current_dev = current_device.load();
|
||||
if current_dev.connect_server.is_ipv4() && current_dev.status.online() {
|
||||
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;
|
||||
@@ -58,10 +97,11 @@ pub fn addr_request0(
|
||||
packet.first_set_ttl(MAX_TTL);
|
||||
packet.set_source(src_ip);
|
||||
packet.set_destination(gateway_ip);
|
||||
if let Err(e) = server_cipher.encrypt_ipv4(&mut packet) {
|
||||
log::warn!("AddrRequest err={:?}", e)
|
||||
} else {
|
||||
context.try_send_all_main(packet.buffer(), current_dev.connect_server);
|
||||
}
|
||||
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)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -167,7 +166,7 @@ fn client_relay0(
|
||||
current_device: &CurrentDeviceInfo,
|
||||
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
|
||||
client_cipher: &Cipher,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
// 离线了不再探测
|
||||
if current_device.status.offline() {
|
||||
return Ok(());
|
||||
@@ -211,7 +210,7 @@ fn client_relay0(
|
||||
fn heartbeat_packet(
|
||||
src: Ipv4Addr,
|
||||
dest: Ipv4Addr,
|
||||
) -> io::Result<NetPacket<[u8; 12 + 4 + ENCRYPTION_RESERVED]>> {
|
||||
) -> anyhow::Result<NetPacket<[u8; 12 + 4 + ENCRYPTION_RESERVED]>> {
|
||||
let mut net_packet = NetPacket::new_encrypt([0u8; 12 + 4 + ENCRYPTION_RESERVED])?;
|
||||
net_packet.set_default_version();
|
||||
net_packet.set_protocol(Protocol::Control);
|
||||
@@ -228,7 +227,7 @@ fn heartbeat_packet_client(
|
||||
client_cipher: &Cipher,
|
||||
src: Ipv4Addr,
|
||||
dest: Ipv4Addr,
|
||||
) -> io::Result<NetPacket<[u8; 12 + 4 + ENCRYPTION_RESERVED]>> {
|
||||
) -> anyhow::Result<NetPacket<[u8; 12 + 4 + ENCRYPTION_RESERVED]>> {
|
||||
let mut net_packet = heartbeat_packet(src, dest)?;
|
||||
client_cipher.encrypt_ipv4(&mut net_packet)?;
|
||||
Ok(net_packet)
|
||||
@@ -239,7 +238,7 @@ fn heartbeat_packet_server(
|
||||
server_cipher: &Cipher,
|
||||
src: Ipv4Addr,
|
||||
dest: Ipv4Addr,
|
||||
) -> io::Result<NetPacket<[u8; 12 + 4 + ENCRYPTION_RESERVED]>> {
|
||||
) -> 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);
|
||||
|
||||
@@ -6,7 +6,7 @@ mod re_nat_type;
|
||||
pub use re_nat_type::retrieve_nat_type;
|
||||
|
||||
mod addr_request;
|
||||
pub use addr_request::addr_request;
|
||||
pub use addr_request::*;
|
||||
|
||||
mod punch;
|
||||
pub use punch::*;
|
||||
|
||||
@@ -2,9 +2,10 @@ use std::collections::HashMap;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::mpsc::{sync_channel, Receiver, SyncSender};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::{io, thread};
|
||||
|
||||
use anyhow::anyhow;
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use protobuf::Message;
|
||||
@@ -222,7 +223,7 @@ fn punch0(
|
||||
punch_record: &Mutex<HashMap<Ipv4Addr, usize>>,
|
||||
last_punch_record: &mut HashMap<Ipv4Addr, usize>,
|
||||
total_count: usize,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let nat_info = nat_test.nat_info();
|
||||
if total_count < 10
|
||||
&& (nat_info.public_ips.is_empty()
|
||||
@@ -297,7 +298,7 @@ fn punch_packet(
|
||||
virtual_ip: Ipv4Addr,
|
||||
nat_info: &NatInfo,
|
||||
dest: Ipv4Addr,
|
||||
) -> io::Result<NetPacket<Vec<u8>>> {
|
||||
) -> anyhow::Result<NetPacket<Vec<u8>>> {
|
||||
let mut punch_reply = PunchInfo::new();
|
||||
punch_reply.reply = false;
|
||||
punch_reply.public_ip_list = nat_info
|
||||
@@ -320,7 +321,7 @@ fn punch_packet(
|
||||
log::info!("请求打洞={:?}", punch_reply);
|
||||
let bytes = punch_reply
|
||||
.write_to_bytes()
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, format!("punch_packet {:?}", e)))?;
|
||||
.map_err(|e| anyhow!("punch_packet {:?}", e))?;
|
||||
let mut net_packet = NetPacket::new_encrypt(vec![0u8; 12 + bytes.len() + ENCRYPTION_RESERVED])?;
|
||||
net_packet.set_default_version();
|
||||
net_packet.set_protocol(Protocol::OtherTurn);
|
||||
|
||||
@@ -2,6 +2,7 @@ use crossbeam_utils::atomic::AtomicCell;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
pub mod callback;
|
||||
mod extension;
|
||||
pub mod handshaker;
|
||||
pub mod maintain;
|
||||
pub mod recv_data;
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
use parking_lot::RwLock;
|
||||
use protobuf::Message;
|
||||
use anyhow::anyhow;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use protobuf::Message;
|
||||
|
||||
use packet::icmp::{icmp, Kind};
|
||||
use packet::ip::ipv4;
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
use tun::device::IFace;
|
||||
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::channel::punch::NatInfo;
|
||||
use crate::channel::{Route, RouteKey};
|
||||
use crate::cipher::Cipher;
|
||||
use crate::external_route::AllowExternalRoute;
|
||||
use crate::handle::extension::handle_extension_tail;
|
||||
use crate::handle::maintain::PunchSender;
|
||||
use crate::handle::recv_data::PacketHandler;
|
||||
use crate::handle::CurrentDeviceInfo;
|
||||
@@ -27,8 +31,6 @@ use crate::protocol::{
|
||||
control_packet, ip_turn_packet, other_turn_packet, NetPacket, Protocol, MAX_TTL,
|
||||
};
|
||||
use crate::tun_tap_device::tun_create_helper::DeviceAdapter;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
use tun::device::IFace;
|
||||
|
||||
/// 处理来源于客户端的包
|
||||
#[derive(Clone)]
|
||||
@@ -70,14 +72,26 @@ impl PacketHandler for ClientPacketHandler {
|
||||
fn handle(
|
||||
&self,
|
||||
mut net_packet: NetPacket<&mut [u8]>,
|
||||
mut extend: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
context: &ChannelContext,
|
||||
current_device: &CurrentDeviceInfo,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
self.client_cipher.decrypt_ipv4(&mut net_packet)?;
|
||||
context
|
||||
.route_table
|
||||
.update_read_time(&net_packet.source(), &route_key);
|
||||
//处理扩展
|
||||
let net_packet = if net_packet.is_extension() {
|
||||
//这样重用数组,减少一次数据拷贝
|
||||
if handle_extension_tail(&mut net_packet, &mut extend)? {
|
||||
extend
|
||||
} else {
|
||||
net_packet
|
||||
}
|
||||
} else {
|
||||
net_packet
|
||||
};
|
||||
match net_packet.protocol() {
|
||||
Protocol::Service => {}
|
||||
Protocol::Error => {}
|
||||
@@ -103,7 +117,7 @@ impl ClientPacketHandler {
|
||||
context: &ChannelContext,
|
||||
current_device: &CurrentDeviceInfo,
|
||||
route_key: RouteKey,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let destination = net_packet.destination();
|
||||
let source = net_packet.source();
|
||||
match ip_turn_packet::Protocol::from(net_packet.transport_protocol()) {
|
||||
@@ -190,7 +204,7 @@ impl ClientPacketHandler {
|
||||
current_device: &CurrentDeviceInfo,
|
||||
mut net_packet: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
let metric = net_packet.source_ttl() - net_packet.ttl() + 1;
|
||||
let source = net_packet.source();
|
||||
match ControlPacket::new(net_packet.transport_protocol(), net_packet.payload())? {
|
||||
@@ -233,8 +247,9 @@ impl ClientPacketHandler {
|
||||
net_packet.first_set_ttl(1);
|
||||
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, 1);
|
||||
context.route_table.add_route_if_absent(source, route);
|
||||
// 收到PunchRequest就添加路由,会导致单向通信的问题,删掉试试
|
||||
// let route = Route::from_default_rt(route_key, 1);
|
||||
// context.route_table.add_route_if_absent(source, route);
|
||||
}
|
||||
ControlPacket::PunchResponse => {
|
||||
log::info!("PunchResponse={:?},source={}", route_key, source);
|
||||
@@ -277,17 +292,15 @@ impl ClientPacketHandler {
|
||||
current_device: &CurrentDeviceInfo,
|
||||
net_packet: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if context.use_channel_type().is_only_relay() {
|
||||
return Ok(());
|
||||
}
|
||||
let source = net_packet.source();
|
||||
match other_turn_packet::Protocol::from(net_packet.transport_protocol()) {
|
||||
other_turn_packet::Protocol::Punch => {
|
||||
let mut punch_info =
|
||||
PunchInfo::parse_from_bytes(net_packet.payload()).map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("PunchInfo {:?}", e))
|
||||
})?;
|
||||
let mut punch_info = PunchInfo::parse_from_bytes(net_packet.payload())
|
||||
.map_err(|e| anyhow!("PunchInfo {:?}", e))?;
|
||||
let public_ips = punch_info
|
||||
.public_ip_list
|
||||
.iter()
|
||||
@@ -347,9 +360,9 @@ impl ClientPacketHandler {
|
||||
punch_reply.ipv6 = ipv6.octets().to_vec();
|
||||
punch_reply.ipv6_port = nat_info.udp_ports[0] as u32;
|
||||
}
|
||||
let bytes = punch_reply.write_to_bytes().map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("punch_reply {:?}", e))
|
||||
})?;
|
||||
let bytes = punch_reply
|
||||
.write_to_bytes()
|
||||
.map_err(|e| anyhow!("punch_reply {:?}", e))?;
|
||||
let mut punch_packet =
|
||||
NetPacket::new_encrypt(vec![0u8; 12 + bytes.len() + ENCRYPTION_RESERVED])?;
|
||||
punch_packet.set_default_version();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::{io, thread};
|
||||
use std::thread;
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
@@ -39,12 +39,35 @@ pub struct RecvDataHandler<Call> {
|
||||
client: ClientPacketHandler,
|
||||
server: ServerPacketHandler<Call>,
|
||||
counter: U64Adder,
|
||||
nat_test: NatTest,
|
||||
}
|
||||
|
||||
impl<Call: VntCallback> RecvChannelHandler for RecvDataHandler<Call> {
|
||||
fn handle(&mut self, buf: &mut [u8], route_key: RouteKey, context: &ChannelContext) {
|
||||
if let Err(e) = self.handle0(buf, route_key, context) {
|
||||
log::error!("[{}]-{:?}", thread::current().name().unwrap_or(""), e);
|
||||
fn handle(
|
||||
&mut self,
|
||||
buf: &mut [u8],
|
||||
extend: &mut [u8],
|
||||
route_key: RouteKey,
|
||||
context: &ChannelContext,
|
||||
) {
|
||||
//判断stun响应包
|
||||
if !route_key.is_tcp() {
|
||||
if let Ok(rs) = self
|
||||
.nat_test
|
||||
.recv_data(route_key.index(), route_key.addr, buf)
|
||||
{
|
||||
if rs {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = self.handle0(buf, extend, route_key, context) {
|
||||
log::error!(
|
||||
"[{}]-{:?}-{:?}",
|
||||
thread::current().name().unwrap_or(""),
|
||||
route_key.addr,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,7 +109,7 @@ impl<Call: VntCallback> RecvDataHandler<Call> {
|
||||
client_cipher,
|
||||
punch_sender,
|
||||
peer_nat_info_map,
|
||||
nat_test,
|
||||
nat_test.clone(),
|
||||
route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
ip_proxy_map,
|
||||
@@ -98,17 +121,20 @@ impl<Call: VntCallback> RecvDataHandler<Call> {
|
||||
client,
|
||||
server,
|
||||
counter,
|
||||
nat_test,
|
||||
}
|
||||
}
|
||||
fn handle0(
|
||||
&mut self,
|
||||
buf: &mut [u8],
|
||||
extend: &mut [u8],
|
||||
route_key: RouteKey,
|
||||
context: &ChannelContext,
|
||||
) -> io::Result<()> {
|
||||
) -> 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());
|
||||
return Ok(());
|
||||
@@ -126,16 +152,16 @@ impl<Call: VntCallback> RecvDataHandler<Call> {
|
||||
if net_packet.is_gateway() {
|
||||
//服务端-客户端包
|
||||
self.server
|
||||
.handle(net_packet, route_key, context, ¤t_device)
|
||||
.handle(net_packet, extend, route_key, context, ¤t_device)
|
||||
} else {
|
||||
//客户端-客户端包
|
||||
self.client
|
||||
.handle(net_packet, route_key, context, ¤t_device)
|
||||
.handle(net_packet, extend, route_key, context, ¤t_device)
|
||||
}
|
||||
} else {
|
||||
//转发包
|
||||
self.turn
|
||||
.handle(net_packet, route_key, context, ¤t_device)
|
||||
.handle(net_packet, extend, route_key, context, ¤t_device)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,8 +170,9 @@ pub trait PacketHandler {
|
||||
fn handle(
|
||||
&self,
|
||||
net_packet: NetPacket<&mut [u8]>,
|
||||
extend: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
context: &ChannelContext,
|
||||
current_device: &CurrentDeviceInfo,
|
||||
) -> io::Result<()>;
|
||||
) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use anyhow::anyhow;
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
@@ -11,6 +12,8 @@ use protobuf::Message;
|
||||
use packet::icmp::{icmp, Kind};
|
||||
use packet::ip::ipv4;
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
use tun::device::IFace;
|
||||
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::channel::{Route, RouteKey};
|
||||
@@ -34,8 +37,6 @@ use crate::protocol::error_packet::InErrorPacket;
|
||||
use crate::protocol::{ip_turn_packet, service_packet, NetPacket, Protocol, MAX_TTL};
|
||||
use crate::tun_tap_device::tun_create_helper::DeviceAdapter;
|
||||
use crate::{proto, PeerClientInfo};
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
use tun::device::IFace;
|
||||
|
||||
/// 处理来源于服务端的包
|
||||
#[derive(Clone)]
|
||||
@@ -94,10 +95,11 @@ impl<Call: VntCallback> PacketHandler for ServerPacketHandler<Call> {
|
||||
fn handle(
|
||||
&self,
|
||||
mut net_packet: NetPacket<&mut [u8]>,
|
||||
_extend: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
context: &ChannelContext,
|
||||
current_device: &CurrentDeviceInfo,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
context
|
||||
.route_table
|
||||
.update_read_time(&net_packet.source(), &route_key);
|
||||
@@ -135,10 +137,8 @@ impl<Call: VntCallback> PacketHandler for ServerPacketHandler<Call> {
|
||||
} else if net_packet.protocol() == Protocol::Service
|
||||
&& net_packet.transport_protocol() == service_packet::Protocol::HandshakeResponse.into()
|
||||
{
|
||||
let response =
|
||||
HandshakeResponse::parse_from_bytes(net_packet.payload()).map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("HandshakeResponse {:?}", e))
|
||||
})?;
|
||||
let response = HandshakeResponse::parse_from_bytes(net_packet.payload())
|
||||
.map_err(|e| anyhow!("HandshakeResponse {:?}", e))?;
|
||||
log::info!("握手响应:{:?},{}", route_key, response);
|
||||
//如果开启了加密,则发送加密握手请求
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
@@ -193,6 +193,7 @@ impl<Call: VntCallback> PacketHandler for ServerPacketHandler<Call> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
#[cfg(feature = "server_encrypt")]
|
||||
if let Ok(rsa_cipher) = RsaCipher::new(&response.public_key) {
|
||||
self.rsa_cipher.lock().replace(rsa_cipher);
|
||||
}
|
||||
@@ -252,7 +253,7 @@ impl<Call: VntCallback> ServerPacketHandler<Call> {
|
||||
current_device: &CurrentDeviceInfo,
|
||||
net_packet: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
match service_packet::Protocol::from(net_packet.transport_protocol()) {
|
||||
service_packet::Protocol::RegistrationResponse => {
|
||||
let response = RegistrationResponse::parse_from_bytes(net_packet.payload())
|
||||
@@ -320,8 +321,7 @@ impl<Call: VntCallback> ServerPacketHandler<Call> {
|
||||
"device_fd == 0".into(),
|
||||
));
|
||||
} else {
|
||||
let device = Arc::new(tun::Device::new(device_fd as _)?);
|
||||
if let Err(e) = self.device.start(device) {
|
||||
if let Err(e) = self.device.start(device_fd as _) {
|
||||
self.callback.error(ErrorInfo::new_msg(
|
||||
ErrorType::Unknown,
|
||||
format!("{:?}", e),
|
||||
@@ -439,7 +439,7 @@ impl<Call: VntCallback> ServerPacketHandler<Call> {
|
||||
&self,
|
||||
current_device: &CurrentDeviceInfo,
|
||||
context: &ChannelContext,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
if current_device.status.online() {
|
||||
log::info!("已连接的不需要注册,{:?}", self.config_info);
|
||||
return Ok(());
|
||||
@@ -468,7 +468,8 @@ impl<Call: VntCallback> ServerPacketHandler<Call> {
|
||||
)?;
|
||||
log::info!("发送注册请求,{:?}", self.config_info);
|
||||
//注册请求只发送到默认通道
|
||||
context.send_default(response.buffer(), current_device.connect_server)
|
||||
context.send_default(response.buffer(), current_device.connect_server)?;
|
||||
Ok(())
|
||||
}
|
||||
fn error(
|
||||
&self,
|
||||
@@ -526,7 +527,7 @@ impl<Call: VntCallback> ServerPacketHandler<Call> {
|
||||
current_device: &CurrentDeviceInfo,
|
||||
net_packet: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
) -> io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
match ControlPacket::new(net_packet.transport_protocol(), net_packet.payload())? {
|
||||
ControlPacket::PongPacket(pong_packet) => {
|
||||
let current_time = crate::handle::now_time() as u16;
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::channel::RouteKey;
|
||||
use crate::handle::recv_data::PacketHandler;
|
||||
use crate::handle::CurrentDeviceInfo;
|
||||
use crate::protocol::NetPacket;
|
||||
use anyhow::Context;
|
||||
|
||||
/// 处理客户端中转包
|
||||
#[derive(Clone)]
|
||||
@@ -18,10 +19,11 @@ impl PacketHandler for TurnPacketHandler {
|
||||
fn handle(
|
||||
&self,
|
||||
mut net_packet: NetPacket<&mut [u8]>,
|
||||
_extend: NetPacket<&mut [u8]>,
|
||||
route_key: RouteKey,
|
||||
context: &ChannelContext,
|
||||
_current_device: &CurrentDeviceInfo,
|
||||
) -> std::io::Result<()> {
|
||||
) -> anyhow::Result<()> {
|
||||
// ttl减一
|
||||
let ttl = net_packet.incr_ttl();
|
||||
if ttl > 0 {
|
||||
@@ -33,7 +35,9 @@ impl PacketHandler for TurnPacketHandler {
|
||||
return Ok(());
|
||||
}
|
||||
if route.metric <= ttl {
|
||||
return context.send_by_key(net_packet.buffer(), route.route_key());
|
||||
return context
|
||||
.send_by_key(net_packet.buffer(), route.route_key())
|
||||
.context("转发失败");
|
||||
}
|
||||
}
|
||||
//其他没有路由的不转发
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::io;
|
||||
use anyhow::anyhow;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use protobuf::Message;
|
||||
@@ -19,7 +19,7 @@ pub fn registration_request_packet(
|
||||
is_fast: bool,
|
||||
allow_ip_change: bool,
|
||||
client_secret_hash: Option<&[u8]>,
|
||||
) -> io::Result<NetPacket<Vec<u8>>> {
|
||||
) -> anyhow::Result<NetPacket<Vec<u8>>> {
|
||||
let mut request = RegistrationRequest::new();
|
||||
request.token = token;
|
||||
request.device_id = device_id;
|
||||
@@ -36,9 +36,9 @@ pub fn registration_request_packet(
|
||||
.client_secret_hash
|
||||
.extend_from_slice(client_secret_hash);
|
||||
}
|
||||
let bytes = request.write_to_bytes().map_err(|e| {
|
||||
io::Error::new(io::ErrorKind::Other, format!("RegistrationRequest {:?}", e))
|
||||
})?;
|
||||
let bytes = request
|
||||
.write_to_bytes()
|
||||
.map_err(|e| anyhow!("RegistrationRequest {:?}", e))?;
|
||||
let buf = vec![0u8; 12 + bytes.len() + ENCRYPTION_RESERVED];
|
||||
let mut net_packet = NetPacket::new_encrypt(buf)?;
|
||||
net_packet.set_destination(GATEWAY_IP);
|
||||
|
||||
@@ -1,187 +1,11 @@
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
use packet::ip::ipv4::protocol::Protocol;
|
||||
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::cipher::Cipher;
|
||||
use crate::external_route::ExternalRoute;
|
||||
use crate::handle::{check_dest, CurrentDeviceInfo, PeerDeviceInfo};
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
use crate::ip_proxy::{IpProxyMap, ProxyHandler};
|
||||
use crate::protocol;
|
||||
use crate::protocol::body::ENCRYPTION_RESERVED;
|
||||
use crate::protocol::ip_turn_packet::BroadcastPacket;
|
||||
use crate::protocol::{ip_turn_packet, NetPacket, MAX_TTL};
|
||||
|
||||
mod channel_group;
|
||||
pub mod tun_handler;
|
||||
|
||||
fn broadcast(
|
||||
server_cipher: &Cipher,
|
||||
sender: &ChannelContext,
|
||||
net_packet: &mut NetPacket<&mut [u8]>,
|
||||
current_device: &CurrentDeviceInfo,
|
||||
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
|
||||
) -> io::Result<()> {
|
||||
let list: Vec<Ipv4Addr> = device_list
|
||||
.lock()
|
||||
.1
|
||||
.iter()
|
||||
.filter(|info| info.status.is_online())
|
||||
.map(|info| info.virtual_ip)
|
||||
.collect();
|
||||
const MAX_COUNT: usize = 8;
|
||||
let mut p2p_ips = Vec::with_capacity(8);
|
||||
let mut relay_ips = Vec::with_capacity(8);
|
||||
let mut overflow = false;
|
||||
for (index, peer_ip) in list.into_iter().enumerate() {
|
||||
if index > MAX_COUNT {
|
||||
overflow = true;
|
||||
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()
|
||||
{
|
||||
p2p_ips.push(peer_ip);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
relay_ips.push(peer_ip);
|
||||
}
|
||||
if !overflow && relay_ips.is_empty() {
|
||||
//全部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(());
|
||||
}
|
||||
let buf = vec![0u8; 12 + 1 + p2p_ips.len() * 4 + net_packet.data_len() + ENCRYPTION_RESERVED];
|
||||
//剩余的发送到服务端,需要告知哪些已发送过
|
||||
let mut server_packet = NetPacket::new_encrypt(buf)?;
|
||||
server_packet.set_default_version();
|
||||
server_packet.set_gateway_flag(true);
|
||||
server_packet.first_set_ttl(MAX_TTL);
|
||||
server_packet.set_source(net_packet.source());
|
||||
//使用对应的目的地址
|
||||
server_packet.set_destination(net_packet.destination());
|
||||
server_packet.set_protocol(protocol::Protocol::IpTurn);
|
||||
server_packet.set_transport_protocol(ip_turn_packet::Protocol::Ipv4Broadcast.into());
|
||||
|
||||
let mut broadcast = BroadcastPacket::unchecked(server_packet.payload_mut());
|
||||
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)
|
||||
}
|
||||
|
||||
/// 实现一个原地发送,必须保证是如下结构
|
||||
/// |12字节开头|ip报文|至少1024字节结尾|
|
||||
///
|
||||
#[inline]
|
||||
pub fn base_handle(
|
||||
context: &ChannelContext,
|
||||
buf: &mut [u8],
|
||||
data_len: usize, //数据总长度=12+ip包长度
|
||||
current_device: CurrentDeviceInfo,
|
||||
ip_route: &ExternalRoute,
|
||||
#[cfg(feature = "ip_proxy")] proxy_map: &Option<IpProxyMap>,
|
||||
client_cipher: &Cipher,
|
||||
server_cipher: &Cipher,
|
||||
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
|
||||
) -> io::Result<()> {
|
||||
let ipv4_packet = IpV4Packet::new(&buf[12..data_len])?;
|
||||
let protocol = ipv4_packet.protocol();
|
||||
let src_ip = ipv4_packet.source_ip();
|
||||
let mut dest_ip = ipv4_packet.destination_ip();
|
||||
let mut net_packet = NetPacket::new0(data_len, 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 dest_ip == current_device.virtual_gateway {
|
||||
// 发到网关的加密方式不一样,要单独处理
|
||||
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)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if dest_ip.is_multicast() {
|
||||
//当作广播处理
|
||||
dest_ip = Ipv4Addr::BROADCAST;
|
||||
net_packet.set_destination(Ipv4Addr::BROADCAST);
|
||||
}
|
||||
if dest_ip.is_broadcast() || current_device.broadcast_ip == dest_ip {
|
||||
// 广播 发送到直连目标
|
||||
client_cipher.encrypt_ipv4(&mut net_packet)?;
|
||||
broadcast(
|
||||
server_cipher,
|
||||
context,
|
||||
&mut net_packet,
|
||||
¤t_device,
|
||||
device_list,
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
if !check_dest(
|
||||
dest_ip,
|
||||
current_device.virtual_netmask,
|
||||
current_device.virtual_network,
|
||||
) {
|
||||
if let Some(r_dest_ip) = ip_route.route(&dest_ip) {
|
||||
//路由的目标不能是自己
|
||||
if r_dest_ip == src_ip {
|
||||
return Ok(());
|
||||
}
|
||||
//需要修改目的地址
|
||||
dest_ip = r_dest_ip;
|
||||
net_packet.set_destination(r_dest_ip);
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
if let Some(proxy_map) = proxy_map {
|
||||
let mut ipv4_packet = IpV4Packet::new(net_packet.payload_mut())?;
|
||||
proxy_map.send_handle(&mut ipv4_packet)?;
|
||||
}
|
||||
client_cipher.encrypt_ipv4(&mut net_packet)?;
|
||||
context.send_ipv4_by_id(
|
||||
net_packet.buffer(),
|
||||
&dest_ip,
|
||||
current_device.connect_server,
|
||||
current_device.status.online(),
|
||||
)
|
||||
}
|
||||
#[cfg(unix)]
|
||||
mod unix;
|
||||
#[cfg(unix)]
|
||||
pub(crate) use unix::*;
|
||||
#[cfg(target_os = "windows")]
|
||||
mod windows;
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) use windows::*;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::{io, thread};
|
||||
|
||||
@@ -6,22 +7,30 @@ use parking_lot::Mutex;
|
||||
|
||||
use packet::icmp::icmp::IcmpPacket;
|
||||
use packet::icmp::Kind;
|
||||
use packet::ip::ipv4;
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
use packet::ip::ipv4::protocol::Protocol;
|
||||
use tun::device::IFace;
|
||||
use tun::Device;
|
||||
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::channel::BUFFER_SIZE;
|
||||
use crate::cipher::Cipher;
|
||||
use crate::compression::Compressor;
|
||||
use crate::external_route::ExternalRoute;
|
||||
use crate::handle::tun_tap::channel_group::{channel_group, GroupSyncSender};
|
||||
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
|
||||
use crate::handle::tun_tap::channel_group::channel_group;
|
||||
use crate::handle::{check_dest, CurrentDeviceInfo, PeerDeviceInfo};
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
use crate::ip_proxy::IpProxyMap;
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
use crate::ip_proxy::ProxyHandler;
|
||||
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};
|
||||
|
||||
fn icmp(device_writer: &Device, mut ipv4_packet: IpV4Packet<&mut [u8]>) -> io::Result<()> {
|
||||
if ipv4_packet.protocol() == ipv4::protocol::Protocol::Icmp {
|
||||
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())?;
|
||||
if icmp.kind() == Kind::EchoRequest {
|
||||
icmp.set_kind(Kind::EchoReply);
|
||||
@@ -36,43 +45,6 @@ fn icmp(device_writer: &Device, mut ipv4_packet: IpV4Packet<&mut [u8]>) -> io::R
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 接收tun数据,并且转发到udp上
|
||||
fn handle(
|
||||
context: &ChannelContext,
|
||||
data: &mut [u8],
|
||||
len: usize,
|
||||
device_writer: &Device,
|
||||
current_device: CurrentDeviceInfo,
|
||||
ip_route: &ExternalRoute,
|
||||
#[cfg(feature = "ip_proxy")] proxy_map: &Option<IpProxyMap>,
|
||||
client_cipher: &Cipher,
|
||||
server_cipher: &Cipher,
|
||||
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
|
||||
) -> io::Result<()> {
|
||||
//忽略掉结构不对的情况(ipv6数据、win tap会读到空数据),不然日志打印太多了
|
||||
let ipv4_packet = match IpV4Packet::new(&mut data[12..len]) {
|
||||
Ok(packet) => packet,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
let src_ip = ipv4_packet.source_ip();
|
||||
let dest_ip = ipv4_packet.destination_ip();
|
||||
if src_ip == dest_ip {
|
||||
return icmp(&device_writer, ipv4_packet);
|
||||
}
|
||||
return crate::handle::tun_tap::base_handle(
|
||||
context,
|
||||
data,
|
||||
len,
|
||||
current_device,
|
||||
ip_route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
proxy_map,
|
||||
client_cipher,
|
||||
server_cipher,
|
||||
device_list,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn start(
|
||||
stop_manager: StopManager,
|
||||
context: ChannelContext,
|
||||
@@ -85,24 +57,8 @@ pub fn start(
|
||||
parallel: usize,
|
||||
mut up_counter: SingleU64Adder,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
compressor: Compressor,
|
||||
) -> io::Result<()> {
|
||||
let worker = {
|
||||
#[cfg(any(target_os = "macos", target_os = "android"))]
|
||||
let current_device = current_device.clone();
|
||||
let device = device.clone();
|
||||
stop_manager.add_listener("tun_device".into(), move || {
|
||||
if let Err(e) = device.shutdown() {
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
#[cfg(any(target_os = "macos", target_os = "android"))]
|
||||
{
|
||||
let ip = current_device.load().virtual_ip;
|
||||
if let Ok(udp) = std::net::UdpSocket::bind("0.0.0.0:0") {
|
||||
let _ = udp.send_to(b"stop", format!("{:?}:1234", ip));
|
||||
}
|
||||
}
|
||||
})?
|
||||
};
|
||||
if parallel > 1 {
|
||||
let (sender, receivers) = channel_group::<(Vec<u8>, usize)>(parallel, 16);
|
||||
for (index, receiver) in receivers.into_iter().enumerate() {
|
||||
@@ -118,6 +74,7 @@ pub fn start(
|
||||
thread::Builder::new()
|
||||
.name(format!("tunHandler-{}", index))
|
||||
.spawn(move || {
|
||||
let mut extend = [0; BUFFER_SIZE];
|
||||
while let Ok((mut buf, len)) = receiver.recv() {
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let start = 0;
|
||||
@@ -127,6 +84,7 @@ pub fn start(
|
||||
&context,
|
||||
&mut buf[start..],
|
||||
len,
|
||||
&mut extend,
|
||||
&device,
|
||||
current_device.load(),
|
||||
&ip_route,
|
||||
@@ -135,6 +93,7 @@ pub fn start(
|
||||
&client_cipher,
|
||||
&server_cipher,
|
||||
&device_list,
|
||||
&compressor,
|
||||
) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
@@ -147,16 +106,20 @@ pub fn start(
|
||||
thread::Builder::new()
|
||||
.name("tunHandlerM".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = start_multi(stop_manager, device, sender, &mut up_counter) {
|
||||
if let Err(e) = crate::handle::tun_tap::start_multi(
|
||||
stop_manager,
|
||||
device,
|
||||
sender,
|
||||
&mut up_counter,
|
||||
) {
|
||||
log::warn!("stop:{}", e);
|
||||
}
|
||||
worker.stop_all();
|
||||
})?;
|
||||
} else {
|
||||
thread::Builder::new()
|
||||
.name("tunHandlerS".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = start_simple(
|
||||
if let Err(e) = crate::handle::tun_tap::start_simple(
|
||||
stop_manager,
|
||||
&context,
|
||||
device,
|
||||
@@ -168,76 +131,209 @@ pub fn start(
|
||||
server_cipher,
|
||||
&mut up_counter,
|
||||
device_list,
|
||||
compressor,
|
||||
) {
|
||||
log::warn!("stop:{}", e);
|
||||
}
|
||||
worker.stop_all();
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_simple(
|
||||
stop_manager: StopManager,
|
||||
context: &ChannelContext,
|
||||
device: Arc<Device>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
ip_route: ExternalRoute,
|
||||
#[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>)>>,
|
||||
) -> io::Result<()> {
|
||||
let mut buf = [0; 1024 * 16];
|
||||
loop {
|
||||
if stop_manager.is_stop() {
|
||||
return Ok(());
|
||||
fn broadcast(
|
||||
server_cipher: &Cipher,
|
||||
sender: &ChannelContext,
|
||||
net_packet: &mut NetPacket<&mut [u8]>,
|
||||
current_device: &CurrentDeviceInfo,
|
||||
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
|
||||
) -> anyhow::Result<()> {
|
||||
let list: Vec<Ipv4Addr> = device_list
|
||||
.lock()
|
||||
.1
|
||||
.iter()
|
||||
.filter(|info| info.status.is_online())
|
||||
.map(|info| info.virtual_ip)
|
||||
.collect();
|
||||
const MAX_COUNT: usize = 8;
|
||||
let mut p2p_ips = Vec::with_capacity(8);
|
||||
let mut relay_ips = Vec::with_capacity(8);
|
||||
let mut overflow = false;
|
||||
for (index, peer_ip) in list.into_iter().enumerate() {
|
||||
if index > MAX_COUNT {
|
||||
overflow = true;
|
||||
break;
|
||||
}
|
||||
let len = device.read(&mut buf[12..])? + 12;
|
||||
//单线程的
|
||||
up_counter.add(len as u64);
|
||||
#[cfg(any(target_os = "macos"))]
|
||||
let mut buf = &mut buf[4..];
|
||||
// buf是重复利用的,需要重置头部
|
||||
buf[..12].fill(0);
|
||||
match handle(
|
||||
context,
|
||||
&mut buf,
|
||||
len,
|
||||
&device,
|
||||
current_device.load(),
|
||||
&ip_route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
&ip_proxy_map,
|
||||
&client_cipher,
|
||||
&server_cipher,
|
||||
&device_list,
|
||||
) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e)
|
||||
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()
|
||||
{
|
||||
p2p_ips.push(peer_ip);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
relay_ips.push(peer_ip);
|
||||
}
|
||||
if !overflow && relay_ips.is_empty() {
|
||||
//全部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(());
|
||||
}
|
||||
let buf = vec![0u8; 12 + 1 + p2p_ips.len() * 4 + net_packet.data_len() + ENCRYPTION_RESERVED];
|
||||
//剩余的发送到服务端,需要告知哪些已发送过
|
||||
let mut server_packet = NetPacket::new_encrypt(buf)?;
|
||||
server_packet.set_default_version();
|
||||
server_packet.set_gateway_flag(true);
|
||||
server_packet.first_set_ttl(MAX_TTL);
|
||||
server_packet.set_source(net_packet.source());
|
||||
//使用对应的目的地址
|
||||
server_packet.set_destination(net_packet.destination());
|
||||
server_packet.set_protocol(protocol::Protocol::IpTurn);
|
||||
server_packet.set_transport_protocol(ip_turn_packet::Protocol::Ipv4Broadcast.into());
|
||||
|
||||
let mut broadcast = BroadcastPacket::unchecked(server_packet.payload_mut());
|
||||
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)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_multi(
|
||||
stop_manager: StopManager,
|
||||
device: Arc<Device>,
|
||||
mut group_sync_sender: GroupSyncSender<(Vec<u8>, usize)>,
|
||||
up_counter: &mut SingleU64Adder,
|
||||
) -> io::Result<()> {
|
||||
loop {
|
||||
if stop_manager.is_stop() {
|
||||
return Ok(());
|
||||
/// 接收tun数据,并且转发到udp上
|
||||
/// 实现一个原地发送,必须保证是如下结构
|
||||
/// |12字节开头|ip报文|至少1024字节结尾|
|
||||
///
|
||||
pub(crate) fn handle(
|
||||
context: &ChannelContext,
|
||||
buf: &mut [u8],
|
||||
data_len: usize, //数据总长度=12+ip包长度
|
||||
extend: &mut [u8],
|
||||
device_writer: &Device,
|
||||
current_device: CurrentDeviceInfo,
|
||||
ip_route: &ExternalRoute,
|
||||
#[cfg(feature = "ip_proxy")] proxy_map: &Option<IpProxyMap>,
|
||||
client_cipher: &Cipher,
|
||||
server_cipher: &Cipher,
|
||||
device_list: &Mutex<(u16, Vec<PeerDeviceInfo>)>,
|
||||
compressor: &Compressor,
|
||||
) -> anyhow::Result<()> {
|
||||
//忽略掉结构不对的情况(ipv6数据、win tap会读到空数据),不然日志打印太多了
|
||||
let ipv4_packet = match IpV4Packet::new(&mut buf[12..data_len]) {
|
||||
Ok(packet) => packet,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
let src_ip = ipv4_packet.source_ip();
|
||||
let dest_ip = ipv4_packet.destination_ip();
|
||||
if src_ip == dest_ip {
|
||||
return icmp(&device_writer, ipv4_packet);
|
||||
}
|
||||
let protocol = ipv4_packet.protocol();
|
||||
let src_ip = ipv4_packet.source_ip();
|
||||
let mut dest_ip = ipv4_packet.destination_ip();
|
||||
let mut net_packet = NetPacket::new0(data_len, buf)?;
|
||||
let mut out = NetPacket::unchecked(extend);
|
||||
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 dest_ip == current_device.virtual_gateway {
|
||||
// 发到网关的加密方式不一样,要单独处理
|
||||
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)?;
|
||||
}
|
||||
let mut buf = vec![0; 1024 * 16];
|
||||
let len = device.read(&mut buf[12..])? + 12;
|
||||
//单线程的
|
||||
up_counter.add(len as u64);
|
||||
if group_sync_sender.send((buf, len)).is_err() {
|
||||
return Ok(());
|
||||
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 let Some(r_dest_ip) = ip_route.route(&dest_ip) {
|
||||
//路由的目标不能是自己
|
||||
if r_dest_ip == src_ip {
|
||||
return Ok(());
|
||||
}
|
||||
//需要修改目的地址
|
||||
dest_ip = r_dest_ip;
|
||||
net_packet.set_destination(r_dest_ip);
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
if let Some(proxy_map) = proxy_map {
|
||||
let mut ipv4_packet = IpV4Packet::new(net_packet.payload_mut())?;
|
||||
proxy_map.send_handle(&mut ipv4_packet)?;
|
||||
}
|
||||
}
|
||||
|
||||
if dest_ip.is_multicast() {
|
||||
//当作广播处理
|
||||
dest_ip = Ipv4Addr::BROADCAST;
|
||||
net_packet.set_destination(Ipv4Addr::BROADCAST);
|
||||
}
|
||||
|
||||
let mut net_packet = if compressor.compress(&net_packet, &mut out)? {
|
||||
out.set_default_version();
|
||||
out.set_protocol(protocol::Protocol::IpTurn);
|
||||
out.set_transport_protocol(ip_turn_packet::Protocol::Ipv4.into());
|
||||
out.first_set_ttl(6);
|
||||
out.set_source(src_ip);
|
||||
out.set_destination(dest_ip);
|
||||
out
|
||||
} else {
|
||||
net_packet
|
||||
};
|
||||
if dest_ip.is_broadcast() || current_device.broadcast_ip == dest_ip {
|
||||
// 广播 发送到直连目标
|
||||
client_cipher.encrypt_ipv4(&mut net_packet)?;
|
||||
broadcast(
|
||||
server_cipher,
|
||||
context,
|
||||
&mut net_packet,
|
||||
¤t_device,
|
||||
device_list,
|
||||
)?;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
client_cipher.encrypt_ipv4(&mut net_packet)?;
|
||||
context.send_ipv4_by_id(
|
||||
net_packet.buffer(),
|
||||
&dest_ip,
|
||||
current_device.connect_server,
|
||||
current_device.status.online(),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::channel::BUFFER_SIZE;
|
||||
use crate::cipher::Cipher;
|
||||
use crate::compression::Compressor;
|
||||
use crate::external_route::ExternalRoute;
|
||||
use crate::handle::tun_tap::channel_group::GroupSyncSender;
|
||||
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
use crate::ip_proxy::IpProxyMap;
|
||||
use crate::util::{SingleU64Adder, 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::io;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::sync::Arc;
|
||||
use tun::Device;
|
||||
|
||||
const STOP: Token = Token(0);
|
||||
const FD: Token = Token(1);
|
||||
|
||||
pub(crate) fn start_simple(
|
||||
stop_manager: StopManager,
|
||||
context: &ChannelContext,
|
||||
device: Arc<Device>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
ip_route: ExternalRoute,
|
||||
#[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>)>>,
|
||||
compressor: Compressor,
|
||||
) -> anyhow::Result<()> {
|
||||
let poll = Poll::new()?;
|
||||
let waker = Arc::new(Waker::new(poll.registry(), STOP)?);
|
||||
let _waker = waker.clone();
|
||||
let worker = stop_manager.add_listener("tun_device".into(), move || {
|
||||
let _ = waker.wake();
|
||||
})?;
|
||||
if let Err(e) = start_simple0(
|
||||
poll,
|
||||
context,
|
||||
device,
|
||||
current_device,
|
||||
ip_route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
ip_proxy_map,
|
||||
client_cipher,
|
||||
server_cipher,
|
||||
up_counter,
|
||||
device_list,
|
||||
compressor,
|
||||
) {
|
||||
log::error!("{:?}", e);
|
||||
};
|
||||
worker.stop_all();
|
||||
drop(_waker);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_simple0(
|
||||
mut poll: Poll,
|
||||
context: &ChannelContext,
|
||||
device: Arc<Device>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
ip_route: ExternalRoute,
|
||||
#[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>)>>,
|
||||
compressor: Compressor,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut buf = [0; BUFFER_SIZE];
|
||||
let mut extend = [0; BUFFER_SIZE];
|
||||
let fd = device.as_tun_fd();
|
||||
fd.set_nonblock()?;
|
||||
SourceFd(&fd.as_raw_fd()).register(poll.registry(), FD, Interest::READABLE)?;
|
||||
let mut evnets = Events::with_capacity(4);
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let start = 12;
|
||||
#[cfg(target_os = "macos")]
|
||||
let start = 12 - 4;
|
||||
loop {
|
||||
poll.poll(&mut evnets, None)?;
|
||||
for event in evnets.iter() {
|
||||
if event.token() == STOP {
|
||||
return Ok(());
|
||||
}
|
||||
loop {
|
||||
let len = match fd.read(&mut buf[start..]) {
|
||||
Ok(len) => len + start,
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
Err(e)?
|
||||
}
|
||||
};
|
||||
//单线程的
|
||||
up_counter.add(len as u64);
|
||||
// buf是重复利用的,需要重置头部
|
||||
buf[..12].fill(0);
|
||||
match crate::handle::tun_tap::tun_handler::handle(
|
||||
context,
|
||||
&mut buf,
|
||||
len,
|
||||
&mut extend,
|
||||
&device,
|
||||
current_device.load(),
|
||||
&ip_route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
&ip_proxy_map,
|
||||
&client_cipher,
|
||||
&server_cipher,
|
||||
&device_list,
|
||||
&compressor,
|
||||
) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("{:?}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start_multi(
|
||||
stop_manager: StopManager,
|
||||
device: Arc<Device>,
|
||||
group_sync_sender: GroupSyncSender<(Vec<u8>, usize)>,
|
||||
up_counter: &mut SingleU64Adder,
|
||||
) -> anyhow::Result<()> {
|
||||
let poll = Poll::new()?;
|
||||
let waker = Arc::new(Waker::new(poll.registry(), STOP)?);
|
||||
let _waker = waker.clone();
|
||||
let worker = stop_manager.add_listener("tun_device".into(), move || {
|
||||
let _ = waker.wake();
|
||||
})?;
|
||||
if let Err(e) = start_multi0(poll, device, group_sync_sender, up_counter) {
|
||||
log::error!("{:?}", e);
|
||||
};
|
||||
worker.stop_all();
|
||||
drop(_waker);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_multi0(
|
||||
mut poll: Poll,
|
||||
device: Arc<Device>,
|
||||
mut group_sync_sender: GroupSyncSender<(Vec<u8>, usize)>,
|
||||
up_counter: &mut SingleU64Adder,
|
||||
) -> anyhow::Result<()> {
|
||||
let fd = device.as_tun_fd();
|
||||
fd.set_nonblock()?;
|
||||
SourceFd(&fd.as_raw_fd()).register(poll.registry(), FD, Interest::READABLE)?;
|
||||
let mut evnets = Events::with_capacity(4);
|
||||
let mut buf = vec![0; 1024 * 16];
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let start = 12;
|
||||
#[cfg(target_os = "macos")]
|
||||
let start = 12 - 4;
|
||||
loop {
|
||||
poll.poll(&mut evnets, None)?;
|
||||
for event in evnets.iter() {
|
||||
if event.token() == STOP {
|
||||
return Ok(());
|
||||
}
|
||||
loop {
|
||||
let len = match fd.read(&mut buf[start..]) {
|
||||
Ok(len) => len + start,
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
Err(e)?
|
||||
}
|
||||
};
|
||||
//单线程的
|
||||
up_counter.add(len as u64);
|
||||
if group_sync_sender.send((buf, len)).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
buf = vec![0; 1024 * 16];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::channel::BUFFER_SIZE;
|
||||
use crate::cipher::Cipher;
|
||||
use crate::compression::Compressor;
|
||||
use crate::external_route::ExternalRoute;
|
||||
use crate::handle::tun_tap::channel_group::GroupSyncSender;
|
||||
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
use crate::ip_proxy::IpProxyMap;
|
||||
use crate::util::{SingleU64Adder, StopManager};
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use tun::device::IFace;
|
||||
use tun::Device;
|
||||
|
||||
pub(crate) fn start_simple(
|
||||
stop_manager: StopManager,
|
||||
context: &ChannelContext,
|
||||
device: Arc<Device>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
ip_route: ExternalRoute,
|
||||
#[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>)>>,
|
||||
compressor: Compressor,
|
||||
) -> anyhow::Result<()> {
|
||||
let worker = {
|
||||
let device = device.clone();
|
||||
stop_manager.add_listener("tun_device".into(), move || {
|
||||
if let Err(e) = device.shutdown() {
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
})?
|
||||
};
|
||||
if let Err(e) = start_simple0(
|
||||
context,
|
||||
device,
|
||||
current_device,
|
||||
ip_route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
ip_proxy_map,
|
||||
client_cipher,
|
||||
server_cipher,
|
||||
up_counter,
|
||||
device_list,
|
||||
compressor,
|
||||
) {
|
||||
log::error!("{:?}", e);
|
||||
}
|
||||
worker.stop_all();
|
||||
Ok(())
|
||||
}
|
||||
fn start_simple0(
|
||||
context: &ChannelContext,
|
||||
device: Arc<Device>,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
ip_route: ExternalRoute,
|
||||
#[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>)>>,
|
||||
compressor: Compressor,
|
||||
) -> 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(
|
||||
context,
|
||||
&mut buf,
|
||||
len,
|
||||
&mut extend,
|
||||
&device,
|
||||
current_device.load(),
|
||||
&ip_route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
&ip_proxy_map,
|
||||
&client_cipher,
|
||||
&server_cipher,
|
||||
&device_list,
|
||||
&compressor,
|
||||
) {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("tun/tap {:?}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn start_multi(
|
||||
stop_manager: StopManager,
|
||||
device: Arc<Device>,
|
||||
group_sync_sender: GroupSyncSender<(Vec<u8>, usize)>,
|
||||
up_counter: &mut SingleU64Adder,
|
||||
) -> anyhow::Result<()> {
|
||||
let worker = {
|
||||
let device = device.clone();
|
||||
stop_manager.add_listener("tun_device_multi".into(), move || {
|
||||
if let Err(e) = device.shutdown() {
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
})?
|
||||
};
|
||||
if let Err(e) = start_multi0(device, group_sync_sender, up_counter) {
|
||||
log::error!("{:?}", e);
|
||||
};
|
||||
worker.stop_all();
|
||||
Ok(())
|
||||
}
|
||||
fn start_multi0(
|
||||
device: Arc<Device>,
|
||||
mut group_sync_sender: GroupSyncSender<(Vec<u8>, usize)>,
|
||||
up_counter: &mut SingleU64Adder,
|
||||
) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let mut buf = vec![0; 1024 * 16];
|
||||
let len = device.read(&mut buf[12..])? + 12;
|
||||
//单线程的
|
||||
up_counter.add(len as u64);
|
||||
if group_sync_sender.send((buf, len)).is_err() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
use anyhow::Context;
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||
use std::sync::Arc;
|
||||
use std::{io, thread};
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use mio::net::UdpSocket;
|
||||
use mio::{Events, Interest, Poll, Token, Waker};
|
||||
use parking_lot::Mutex;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
use packet::icmp::icmp;
|
||||
use packet::icmp::icmp::HeaderOther;
|
||||
@@ -18,7 +18,6 @@ use crate::handle::CurrentDeviceInfo;
|
||||
use crate::ip_proxy::ProxyHandler;
|
||||
use crate::protocol;
|
||||
use crate::protocol::{NetPacket, MAX_TTL};
|
||||
use crate::util::StopManager;
|
||||
#[derive(Clone)]
|
||||
pub struct IcmpProxy {
|
||||
icmp_socket: Arc<std::net::UdpSocket>,
|
||||
@@ -27,48 +26,50 @@ pub struct IcmpProxy {
|
||||
}
|
||||
|
||||
impl IcmpProxy {
|
||||
pub fn new(
|
||||
pub async fn new(
|
||||
context: ChannelContext,
|
||||
stop_manager: StopManager,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
client_cipher: Cipher,
|
||||
) -> io::Result<Self> {
|
||||
) -> anyhow::Result<Self> {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
let icmp_socket = socket2::Socket::new(
|
||||
socket2::Domain::IPV4,
|
||||
socket2::Type::RAW,
|
||||
Some(socket2::Protocol::ICMPV4),
|
||||
)?;
|
||||
)
|
||||
.context("new Socket RAW ICMPV4 failed")?;
|
||||
#[cfg(target_os = "android")]
|
||||
let icmp_socket = socket2::Socket::new(
|
||||
socket2::Domain::IPV4,
|
||||
socket2::Type::DGRAM,
|
||||
Some(socket2::Protocol::ICMPV4),
|
||||
)?;
|
||||
)
|
||||
.context("new Socket DGRAM ICMPV4 failed")?;
|
||||
let addr: SocketAddrV4 = SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0);
|
||||
icmp_socket.bind(&socket2::SockAddr::from(addr))?;
|
||||
icmp_socket
|
||||
.bind(&socket2::SockAddr::from(addr))
|
||||
.context("bind Socket ICMPV4 failed")?;
|
||||
icmp_socket.set_nonblocking(true)?;
|
||||
let std_socket: std::net::UdpSocket = icmp_socket.into();
|
||||
let mio_icmp_socket = UdpSocket::from_std(std_socket.try_clone()?);
|
||||
|
||||
let tokio_icmp_socket = UdpSocket::from_std(std_socket.try_clone()?)?;
|
||||
let nat_map: Arc<Mutex<HashMap<(Ipv4Addr, u16, u16), Ipv4Addr>>> =
|
||||
Arc::new(Mutex::new(HashMap::with_capacity(16)));
|
||||
{
|
||||
let nat_map = nat_map.clone();
|
||||
thread::Builder::new()
|
||||
.name("icmpProxy".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = icmp_proxy(
|
||||
mio_icmp_socket,
|
||||
nat_map,
|
||||
context,
|
||||
stop_manager,
|
||||
current_device,
|
||||
client_cipher,
|
||||
) {
|
||||
log::warn!("icmp_proxy:{:?}", e);
|
||||
}
|
||||
})
|
||||
.expect("icmpProxy");
|
||||
tokio::spawn(async {
|
||||
if let Err(e) = icmp_proxy(
|
||||
tokio_icmp_socket,
|
||||
nat_map,
|
||||
context,
|
||||
current_device,
|
||||
client_cipher,
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::warn!("icmp_proxy:{:?}", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(Self {
|
||||
icmp_socket: Arc::new(std_socket),
|
||||
@@ -77,78 +78,21 @@ impl IcmpProxy {
|
||||
}
|
||||
}
|
||||
|
||||
const SERVER_VAL: usize = 0;
|
||||
const SERVER: Token = Token(SERVER_VAL);
|
||||
const NOTIFY_VAL: usize = 1;
|
||||
const NOTIFY: Token = Token(NOTIFY_VAL);
|
||||
|
||||
fn icmp_proxy(
|
||||
mut icmp_socket: UdpSocket,
|
||||
async fn icmp_proxy(
|
||||
icmp_socket: UdpSocket,
|
||||
// 对端-> 真实来源
|
||||
nat_map: Arc<Mutex<HashMap<(Ipv4Addr, u16, u16), Ipv4Addr>>>,
|
||||
context: ChannelContext,
|
||||
stop_manager: StopManager,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
client_cipher: Cipher,
|
||||
) -> io::Result<()> {
|
||||
let mut poll = Poll::new()?;
|
||||
poll.registry()
|
||||
.register(&mut icmp_socket, SERVER, Interest::READABLE)?;
|
||||
let mut events = Events::with_capacity(32);
|
||||
let stop = Arc::new(Waker::new(poll.registry(), NOTIFY)?);
|
||||
let _stop = stop.clone();
|
||||
let _worker = stop_manager.add_listener("icmp_proxy".into(), move || {
|
||||
if let Err(e) = stop.wake() {
|
||||
log::warn!("stop icmp_proxy:{:?}", e);
|
||||
}
|
||||
})?;
|
||||
let mut buf = [0u8; 65535 - 20 - 8];
|
||||
loop {
|
||||
poll.poll(&mut events, None)?;
|
||||
if stop_manager.is_stop() {
|
||||
return Ok(());
|
||||
}
|
||||
for event in events.iter() {
|
||||
match event.token() {
|
||||
SERVER => readable_handle(
|
||||
&icmp_socket,
|
||||
&mut buf,
|
||||
&nat_map,
|
||||
&context,
|
||||
¤t_device,
|
||||
&client_cipher,
|
||||
),
|
||||
NOTIFY => {
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn readable_handle(
|
||||
icmp_socket: &UdpSocket,
|
||||
buf: &mut [u8],
|
||||
nat_map: &Mutex<HashMap<(Ipv4Addr, u16, u16), Ipv4Addr>>,
|
||||
context: &ChannelContext,
|
||||
current_device: &AtomicCell<CurrentDeviceInfo>,
|
||||
client_cipher: &Cipher,
|
||||
) {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
let start = 12;
|
||||
#[cfg(target_os = "android")]
|
||||
let start = 12 + 20;
|
||||
loop {
|
||||
let (len, addr) = match icmp_socket.recv_from(&mut buf[start..]) {
|
||||
Ok(rs) => rs,
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
log::warn!("icmp_socket {:?}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (len, addr) = icmp_socket.recv_from(&mut buf[start..]).await?;
|
||||
if let IpAddr::V4(peer_ip) = addr.ip() {
|
||||
#[cfg(target_os = "android")]
|
||||
{
|
||||
@@ -165,7 +109,7 @@ fn readable_handle(
|
||||
ipv4.set_source_ip(peer_ip);
|
||||
}
|
||||
recv_handle(
|
||||
buf,
|
||||
&mut buf,
|
||||
start + len,
|
||||
peer_ip,
|
||||
&nat_map,
|
||||
@@ -176,6 +120,7 @@ fn readable_handle(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recv_handle(
|
||||
buf: &mut [u8],
|
||||
data_len: usize,
|
||||
@@ -219,11 +164,17 @@ fn recv_handle(
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
h => {
|
||||
log::debug!("不支持的icmp代理 {:?},{:?}", peer_ip, h)
|
||||
}
|
||||
},
|
||||
Err(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("icmp {:?}", e)
|
||||
}
|
||||
},
|
||||
Err(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("icmp {:?}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+40
-7
@@ -1,6 +1,6 @@
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::{io, thread};
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
|
||||
@@ -10,11 +10,13 @@ use packet::ip::ipv4::packet::IpV4Packet;
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::cipher::Cipher;
|
||||
use crate::handle::CurrentDeviceInfo;
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
use crate::ip_proxy::icmp_proxy::IcmpProxy;
|
||||
use crate::ip_proxy::tcp_proxy::TcpProxy;
|
||||
use crate::ip_proxy::udp_proxy::UdpProxy;
|
||||
use crate::util::{Scheduler, StopManager};
|
||||
use crate::util::StopManager;
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
pub mod icmp_proxy;
|
||||
pub mod tcp_proxy;
|
||||
pub mod udp_proxy;
|
||||
@@ -31,6 +33,7 @@ pub trait ProxyHandler {
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct IpProxyMap {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
icmp_proxy: IcmpProxy,
|
||||
tcp_proxy: TcpProxy,
|
||||
udp_proxy: UdpProxy,
|
||||
@@ -38,16 +41,44 @@ pub struct IpProxyMap {
|
||||
|
||||
pub fn init_proxy(
|
||||
context: ChannelContext,
|
||||
scheduler: Scheduler,
|
||||
stop_manager: StopManager,
|
||||
current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
client_cipher: Cipher,
|
||||
) -> io::Result<IpProxyMap> {
|
||||
let icmp_proxy = IcmpProxy::new(context, stop_manager.clone(), current_device, client_cipher)?;
|
||||
let tcp_proxy = TcpProxy::new(stop_manager.clone())?;
|
||||
let udp_proxy = UdpProxy::new(scheduler, stop_manager)?;
|
||||
) -> anyhow::Result<IpProxyMap> {
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.thread_name("ipProxy")
|
||||
.build()?;
|
||||
let proxy_map = runtime.block_on(init_proxy0(context, current_device, client_cipher))?;
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel::<()>();
|
||||
let worker = stop_manager.add_listener("ipProxy".into(), move || {
|
||||
let _ = sender.send(());
|
||||
})?;
|
||||
thread::Builder::new()
|
||||
.name("ipProxy".into())
|
||||
.spawn(move || {
|
||||
runtime.block_on(async {
|
||||
let _ = receiver.await;
|
||||
});
|
||||
runtime.shutdown_background();
|
||||
drop(worker);
|
||||
})?;
|
||||
|
||||
return Ok(proxy_map);
|
||||
}
|
||||
|
||||
async fn init_proxy0(
|
||||
_context: ChannelContext,
|
||||
_current_device: Arc<AtomicCell<CurrentDeviceInfo>>,
|
||||
_client_cipher: Cipher,
|
||||
) -> anyhow::Result<IpProxyMap> {
|
||||
#[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?;
|
||||
|
||||
Ok(IpProxyMap {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
icmp_proxy,
|
||||
tcp_proxy,
|
||||
udp_proxy,
|
||||
@@ -64,6 +95,7 @@ impl ProxyHandler for IpProxyMap {
|
||||
match ipv4.protocol() {
|
||||
ipv4::protocol::Protocol::Tcp => self.tcp_proxy.recv_handle(ipv4, source, destination),
|
||||
ipv4::protocol::Protocol::Udp => self.udp_proxy.recv_handle(ipv4, source, destination),
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
ipv4::protocol::Protocol::Icmp => {
|
||||
self.icmp_proxy.recv_handle(ipv4, source, destination)
|
||||
}
|
||||
@@ -84,6 +116,7 @@ impl ProxyHandler for IpProxyMap {
|
||||
match ipv4.protocol() {
|
||||
ipv4::protocol::Protocol::Tcp => self.tcp_proxy.send_handle(ipv4),
|
||||
ipv4::protocol::Protocol::Udp => self.udp_proxy.send_handle(ipv4),
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
ipv4::protocol::Protocol::Icmp => self.icmp_proxy.send_handle(ipv4),
|
||||
_ => Ok(()),
|
||||
}
|
||||
|
||||
+60
-368
@@ -1,28 +1,16 @@
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{Ipv4Addr, Shutdown, SocketAddrV4};
|
||||
#[cfg(unix)]
|
||||
use std::os::fd::AsRawFd;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::io::AsRawSocket;
|
||||
use anyhow::Context;
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::{collections::HashMap, io, net::SocketAddr, thread};
|
||||
use std::{collections::HashMap, io, net::SocketAddr};
|
||||
|
||||
use bytes::{BufMut, BytesMut};
|
||||
use mio::net::TcpStream;
|
||||
use mio::{net::TcpListener, Events, Interest, Poll, Registry, Token, Waker};
|
||||
use parking_lot::Mutex;
|
||||
use tokio::net::{TcpListener, TcpSocket, TcpStream};
|
||||
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
use packet::tcp::tcp::TcpPacket;
|
||||
|
||||
use crate::ip_proxy::ProxyHandler;
|
||||
use crate::util::StopManager;
|
||||
|
||||
const SERVER_VAL: usize = 0;
|
||||
const SERVER: Token = Token(SERVER_VAL);
|
||||
const NOTIFY_VAL: usize = 1;
|
||||
const NOTIFY: Token = Token(NOTIFY_VAL);
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct TcpProxy {
|
||||
@@ -31,21 +19,16 @@ pub struct TcpProxy {
|
||||
}
|
||||
|
||||
impl TcpProxy {
|
||||
pub fn new(stop_manager: StopManager) -> io::Result<Self> {
|
||||
pub async fn new() -> 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).parse().unwrap())?;
|
||||
let tcp_listener = TcpListener::bind(format!("0.0.0.0:{}", 0))
|
||||
.await
|
||||
.context("TcpProxy bind failed")?;
|
||||
let port = tcp_listener.local_addr()?.port();
|
||||
{
|
||||
let nat_map = nat_map.clone();
|
||||
thread::Builder::new()
|
||||
.name("tcpProxy".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = tcp_proxy(tcp_listener, nat_map, stop_manager) {
|
||||
log::warn!("tcp_proxy:{:?}", e);
|
||||
}
|
||||
})
|
||||
.expect("tcpProxy");
|
||||
tokio::spawn(tcp_proxy(tcp_listener, nat_map));
|
||||
}
|
||||
Ok(Self { port, nat_map })
|
||||
}
|
||||
@@ -93,365 +76,74 @@ impl ProxyHandler for TcpProxy {
|
||||
}
|
||||
}
|
||||
|
||||
fn tcp_proxy(
|
||||
mut tcp_listener: TcpListener,
|
||||
async fn tcp_proxy(
|
||||
tcp_listener: TcpListener,
|
||||
nat_map: Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>>,
|
||||
stop_manager: StopManager,
|
||||
) -> io::Result<()> {
|
||||
let mut poll = Poll::new()?;
|
||||
poll.registry()
|
||||
.register(&mut tcp_listener, SERVER, Interest::READABLE)?;
|
||||
let mut events = Events::with_capacity(32);
|
||||
let mut tcp_map: HashMap<usize, ProxyValue> = HashMap::with_capacity(16);
|
||||
let mut mapping: HashMap<usize, usize> = HashMap::with_capacity(16);
|
||||
let stop = Arc::new(Waker::new(poll.registry(), NOTIFY)?);
|
||||
let _stop = stop.clone();
|
||||
let _worker = stop_manager.add_listener("tcp_proxy".into(), move || {
|
||||
if let Err(e) = stop.wake() {
|
||||
log::warn!("stop tcp_proxy:{:?}", e);
|
||||
}
|
||||
})?;
|
||||
loop {
|
||||
poll.poll(&mut events, None)?;
|
||||
if stop_manager.is_stop() {
|
||||
return Ok(());
|
||||
}
|
||||
for event in events.iter() {
|
||||
match event.token() {
|
||||
SERVER => {
|
||||
accept_handle(
|
||||
poll.registry(),
|
||||
&tcp_listener,
|
||||
&nat_map,
|
||||
&mut tcp_map,
|
||||
&mut mapping,
|
||||
);
|
||||
}
|
||||
NOTIFY => {
|
||||
return Ok(());
|
||||
}
|
||||
Token(index) => {
|
||||
let (val, src_index) = if let Some(v) = tcp_map.get_mut(&index) {
|
||||
(v, index)
|
||||
} else {
|
||||
if let Some(dest_index) = mapping.get(&index) {
|
||||
if let Some(v) = tcp_map.get_mut(dest_index) {
|
||||
(v, *dest_index)
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let (stream1, stream2, buf1, buf2, state1, state2) = val.as_mut(index);
|
||||
if event.is_readable() {
|
||||
if let Err(_) = readable_handle(stream1, stream2, buf1, state2) {
|
||||
*state1 |= READ_CLOSED;
|
||||
}
|
||||
}
|
||||
if event.is_writable() {
|
||||
let read = buf2.len() >= BUF_LEN;
|
||||
if let Err(_) = writable_handle(stream1, buf2) {
|
||||
*state1 |= WRITE_CLOSED;
|
||||
} else if read {
|
||||
if readable_handle(stream2, stream1, buf2, state1).is_err() {
|
||||
*state2 |= READ_CLOSED;
|
||||
}
|
||||
}
|
||||
}
|
||||
if event.is_read_closed() || event.is_error() {
|
||||
*state1 |= READ_CLOSED;
|
||||
}
|
||||
if event.is_write_closed() || event.is_error() {
|
||||
*state1 |= WRITE_CLOSED;
|
||||
}
|
||||
if is_write_closed(*state1) {
|
||||
let _ = stream1.shutdown(Shutdown::Write);
|
||||
let _ = stream2.shutdown(Shutdown::Read);
|
||||
}
|
||||
if is_read_closed(*state1) {
|
||||
let _ = stream1.shutdown(Shutdown::Read);
|
||||
if buf1.is_empty() {
|
||||
let _ = stream2.shutdown(Shutdown::Write);
|
||||
}
|
||||
}
|
||||
if (is_both_closed(*state1) && buf1.is_empty())
|
||||
|| (is_both_closed(*state2) && buf2.is_empty())
|
||||
|| (is_write_closed(*state1) && is_write_closed(*state2)
|
||||
|| (is_read_closed(*state1)
|
||||
&& is_read_closed(*state2)
|
||||
&& buf1.is_empty()
|
||||
&& buf2.is_empty()))
|
||||
{
|
||||
close(src_index, &mut tcp_map, &mut mapping);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn accept_handle(
|
||||
registry: &Registry,
|
||||
tcp_listener: &TcpListener,
|
||||
nat_map: &Mutex<HashMap<SocketAddrV4, SocketAddrV4>>,
|
||||
tcp_map: &mut HashMap<usize, ProxyValue>,
|
||||
mapping: &mut HashMap<usize, usize>,
|
||||
) {
|
||||
loop {
|
||||
match tcp_listener.accept() {
|
||||
Ok((mut src_stream, addr)) => {
|
||||
#[cfg(windows)]
|
||||
let src_fd = src_stream.as_raw_socket() as usize;
|
||||
#[cfg(unix)]
|
||||
let src_fd = src_stream.as_raw_fd() as usize;
|
||||
if src_fd == SERVER_VAL || src_fd == NOTIFY_VAL {
|
||||
log::error!("fd错误:{:?}", src_fd);
|
||||
continue;
|
||||
}
|
||||
let addr = match addr {
|
||||
SocketAddr::V4(addr) => addr,
|
||||
SocketAddr::V6(_) => {
|
||||
// 忽略ipv6
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let _ = src_stream.set_nodelay(false);
|
||||
if let Some(dest_addr) = nat_map.lock().get(&addr).cloned() {
|
||||
match tcp_connect(addr.port(), dest_addr.into()) {
|
||||
Ok(mut dest_stream) => {
|
||||
#[cfg(windows)]
|
||||
let dest_fd = dest_stream.as_raw_socket() as usize;
|
||||
#[cfg(unix)]
|
||||
let dest_fd = dest_stream.as_raw_fd() as usize;
|
||||
if dest_fd == SERVER_VAL || dest_fd == NOTIFY_VAL {
|
||||
log::error!("fd错误:{:?}", dest_fd);
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = registry.register(
|
||||
&mut src_stream,
|
||||
Token(src_fd),
|
||||
Interest::READABLE.add(Interest::WRITABLE),
|
||||
) {
|
||||
log::error!("register src_stream:{:?}", e);
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = registry.register(
|
||||
&mut dest_stream,
|
||||
Token(dest_fd),
|
||||
Interest::READABLE.add(Interest::WRITABLE),
|
||||
) {
|
||||
log::error!("register dest_stream:{:?}", e);
|
||||
continue;
|
||||
}
|
||||
tcp_map.insert(
|
||||
src_fd,
|
||||
ProxyValue::new(src_stream, dest_stream, src_fd, dest_fd),
|
||||
);
|
||||
mapping.insert(dest_fd, src_fd);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("connect:{:?} {}->{}", e, addr, dest_addr);
|
||||
}
|
||||
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() {
|
||||
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;
|
||||
}
|
||||
};
|
||||
proxy(sender_addr, dest_addr, tcp_stream, peer_tcp_stream).await
|
||||
});
|
||||
} else {
|
||||
log::warn!("tcp代理异常: 来源:{},未找到目标", sender_addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
SocketAddr::V6(_) => {}
|
||||
},
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
log::error!("accept:{:?}", e);
|
||||
log::warn!("tcp代理监听:{:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tcp_connect(src_port: u16, addr: SocketAddr) -> io::Result<TcpStream> {
|
||||
let socket = socket2::Socket::new(
|
||||
socket2::Domain::IPV4,
|
||||
socket2::Type::STREAM,
|
||||
Some(socket2::Protocol::TCP),
|
||||
)?;
|
||||
/// 优先使用来源端口建立tcp连接
|
||||
async fn tcp_connect(src_port: u16, addr: SocketAddr) -> anyhow::Result<TcpStream> {
|
||||
let socket = TcpSocket::new_v4()?;
|
||||
if socket
|
||||
.bind(&SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, src_port).into())
|
||||
.bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, src_port).into())
|
||||
.is_err()
|
||||
{
|
||||
socket.bind(&SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into())?;
|
||||
}
|
||||
if let Err(e) = socket.set_tcp_keepalive(
|
||||
&socket2::TcpKeepalive::new()
|
||||
.with_time(Duration::from_secs(120))
|
||||
.with_interval(Duration::from_secs(10)),
|
||||
) {
|
||||
log::warn!("set_tcp_keepalive err {:?}", e);
|
||||
socket.bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into())?;
|
||||
}
|
||||
let _ = socket.set_nodelay(false);
|
||||
socket.connect_timeout(&addr.into(), Duration::from_secs(3))?;
|
||||
socket.set_nonblocking(true)?;
|
||||
Ok(TcpStream::from_std(socket.into()))
|
||||
let tcp_stream = tokio::time::timeout(Duration::from_secs(5), socket.connect(addr))
|
||||
.await
|
||||
.with_context(|| format!("TCP connection timeout {}", addr))?
|
||||
.with_context(|| format!("TCP connection target failed {}", addr))?;
|
||||
Ok(tcp_stream)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ProxyValue {
|
||||
src_stream: TcpStream,
|
||||
dest_stream: TcpStream,
|
||||
src_fd: usize,
|
||||
dest_fd: usize,
|
||||
src_buf: BytesMut,
|
||||
dest_buf: BytesMut,
|
||||
src_state: u8,
|
||||
dest_state: u8,
|
||||
}
|
||||
|
||||
const BUF_LEN: usize = 65536;
|
||||
|
||||
impl ProxyValue {
|
||||
fn new(src_stream: TcpStream, dest_stream: TcpStream, src_fd: usize, dest_fd: usize) -> Self {
|
||||
Self {
|
||||
src_stream,
|
||||
dest_stream,
|
||||
src_fd,
|
||||
dest_fd,
|
||||
src_buf: BytesMut::with_capacity(BUF_LEN),
|
||||
dest_buf: BytesMut::with_capacity(BUF_LEN),
|
||||
src_state: NORMAL,
|
||||
dest_state: NORMAL,
|
||||
}
|
||||
}
|
||||
fn as_mut(
|
||||
&mut self,
|
||||
index: usize,
|
||||
) -> (
|
||||
&mut TcpStream,
|
||||
&mut TcpStream,
|
||||
&mut BytesMut,
|
||||
&mut BytesMut,
|
||||
&mut u8,
|
||||
&mut u8,
|
||||
) {
|
||||
if index == self.src_fd {
|
||||
(
|
||||
&mut self.src_stream,
|
||||
&mut self.dest_stream,
|
||||
&mut self.src_buf,
|
||||
&mut self.dest_buf,
|
||||
&mut self.src_state,
|
||||
&mut self.dest_state,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
&mut self.dest_stream,
|
||||
&mut self.src_stream,
|
||||
&mut self.dest_buf,
|
||||
&mut self.src_buf,
|
||||
&mut self.dest_state,
|
||||
&mut self.src_state,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn readable_handle(
|
||||
stream1: &mut TcpStream,
|
||||
stream2: &mut TcpStream,
|
||||
mid_buf: &mut BytesMut,
|
||||
state2: &mut u8,
|
||||
) -> io::Result<()> {
|
||||
let mut buf = [0; BUF_LEN];
|
||||
|
||||
loop {
|
||||
if mid_buf.len() >= BUF_LEN {
|
||||
// 达到上限不再继续读取
|
||||
return Ok(());
|
||||
}
|
||||
match stream1.read(&mut buf) {
|
||||
Ok(len) => {
|
||||
if len == 0 {
|
||||
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
|
||||
}
|
||||
let mut buf = &buf[..len];
|
||||
if mid_buf.is_empty() {
|
||||
// 直接写入,避免在buf中过渡
|
||||
while !buf.is_empty() {
|
||||
match stream2.write(buf) {
|
||||
Ok(end) => {
|
||||
if end == 0 {
|
||||
*state2 |= WRITE_CLOSED;
|
||||
return Err(io::Error::from(io::ErrorKind::WriteZero));
|
||||
}
|
||||
buf = &buf[end..];
|
||||
}
|
||||
Err(e) => {
|
||||
if e.kind() != io::ErrorKind::WouldBlock {
|
||||
*state2 |= WRITE_CLOSED;
|
||||
return Err(e);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if buf.is_empty() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
mid_buf.reserve(buf.len());
|
||||
mid_buf.put_slice(buf);
|
||||
}
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn writable_handle(stream: &mut TcpStream, mid_buf: &mut BytesMut) -> io::Result<()> {
|
||||
while !mid_buf.is_empty() {
|
||||
match stream.write(&mid_buf) {
|
||||
Ok(len) => {
|
||||
let _ = mid_buf.split_to(len);
|
||||
}
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn close(
|
||||
index: usize,
|
||||
tcp_map: &mut HashMap<usize, ProxyValue>,
|
||||
mapping: &mut HashMap<usize, usize>,
|
||||
async fn proxy(
|
||||
sender_addr: SocketAddrV4,
|
||||
dest_addr: SocketAddrV4,
|
||||
client: TcpStream,
|
||||
server: TcpStream,
|
||||
) {
|
||||
if let Some(val) = tcp_map.remove(&index) {
|
||||
let _ = val.src_stream.shutdown(Shutdown::Both);
|
||||
let _ = val.dest_stream.shutdown(Shutdown::Both);
|
||||
mapping.remove(&val.src_fd);
|
||||
mapping.remove(&val.dest_fd);
|
||||
let (mut client_read, mut client_write) = client.into_split();
|
||||
let (mut server_read, mut server_write) = server.into_split();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = tokio::io::copy(&mut client_read, &mut server_write).await {
|
||||
log::warn!("client tcp proxy {}->{},{:?}", sender_addr, dest_addr, e);
|
||||
}
|
||||
});
|
||||
if let Err(e) = tokio::io::copy(&mut server_read, &mut client_write).await {
|
||||
log::warn!("server tcp proxy {}->{},{:?}", sender_addr, dest_addr, e);
|
||||
}
|
||||
}
|
||||
|
||||
const NORMAL: u8 = 0b00;
|
||||
const READ_CLOSED: u8 = 0b01;
|
||||
const WRITE_CLOSED: u8 = 0b10;
|
||||
const BOTH_CLOSED: u8 = 0b11;
|
||||
|
||||
fn is_read_closed(state: u8) -> bool {
|
||||
(state & READ_CLOSED == READ_CLOSED) || is_both_closed(state)
|
||||
}
|
||||
|
||||
fn is_write_closed(state: u8) -> bool {
|
||||
(state & WRITE_CLOSED == WRITE_CLOSED) || is_both_closed(state)
|
||||
}
|
||||
|
||||
fn is_both_closed(state: u8) -> bool {
|
||||
state & BOTH_CLOSED == BOTH_CLOSED
|
||||
}
|
||||
|
||||
+97
-240
@@ -1,30 +1,17 @@
|
||||
use anyhow::Context;
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
#[cfg(unix)]
|
||||
use std::os::fd::AsRawFd;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::io::AsRawSocket;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{collections::HashMap, io, net::SocketAddr, rc::Rc, thread};
|
||||
use std::{collections::HashMap, io, net::SocketAddr};
|
||||
|
||||
use mio::{net::UdpSocket, Events, Interest, Poll, Token};
|
||||
use mio::{Registry, Waker};
|
||||
use parking_lot::Mutex;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
use packet::ip::ipv4::packet::IpV4Packet;
|
||||
use packet::udp::udp::UdpPacket;
|
||||
|
||||
use crate::ip_proxy::ProxyHandler;
|
||||
use crate::util::{Scheduler, StopManager};
|
||||
|
||||
const SERVER_VAL: usize = 0;
|
||||
const SERVER: Token = Token(SERVER_VAL);
|
||||
const NOTIFY_VAL: usize = 1;
|
||||
const NOTIFY: Token = Token(NOTIFY_VAL);
|
||||
// 开了ip代理后使用mstsc,mstsc会误以为在真实局域网,从而不维护udp心跳,导致断连,所以这里尽量长一点过期时间
|
||||
const NAT_TIMEOUT: Duration = Duration::from_secs(20 * 60);
|
||||
const NAT_FAST_TIMEOUT: Duration = Duration::from_secs(5 * 60);
|
||||
const NAT_MAX: usize = 5_000;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct UdpProxy {
|
||||
@@ -33,21 +20,20 @@ pub struct UdpProxy {
|
||||
}
|
||||
|
||||
impl UdpProxy {
|
||||
pub fn new(scheduler: Scheduler, stop_manager: StopManager) -> io::Result<Self> {
|
||||
pub async fn new() -> 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).parse().unwrap())?;
|
||||
let udp = UdpSocket::bind(format!("0.0.0.0:{}", 0))
|
||||
.await
|
||||
.context("UdpProxy bind failed")?;
|
||||
let port = udp.local_addr()?.port();
|
||||
{
|
||||
let nat_map = nat_map.clone();
|
||||
thread::Builder::new()
|
||||
.name("udpProxy".into())
|
||||
.spawn(move || {
|
||||
if let Err(e) = udp_proxy(udp, nat_map, scheduler, stop_manager) {
|
||||
log::warn!("udp_proxy:{:?}", e);
|
||||
}
|
||||
})
|
||||
.expect("udpProxy");
|
||||
tokio::spawn(async {
|
||||
if let Err(e) = udp_proxy(udp, nat_map).await {
|
||||
log::warn!("udp_proxy:{:?}", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(Self { port, nat_map })
|
||||
}
|
||||
@@ -95,230 +81,101 @@ impl ProxyHandler for UdpProxy {
|
||||
}
|
||||
}
|
||||
|
||||
fn udp_proxy(
|
||||
mut udp: UdpSocket,
|
||||
async fn udp_proxy(
|
||||
udp: UdpSocket,
|
||||
nat_map: Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>>,
|
||||
scheduler: Scheduler,
|
||||
stop_manager: StopManager,
|
||||
) -> io::Result<()> {
|
||||
let mut poll = Poll::new()?;
|
||||
let mut buf = [0u8; 65536];
|
||||
|
||||
poll.registry()
|
||||
.register(&mut udp, SERVER, Interest::READABLE)?;
|
||||
let mut events = Events::with_capacity(32);
|
||||
let mut buf = [0; 65536];
|
||||
let mut token_map: HashMap<Token, (Rc<UdpSocket>, SocketAddrV4, Instant)> =
|
||||
HashMap::with_capacity(64);
|
||||
let mut udp_map: HashMap<SocketAddrV4, (Rc<UdpSocket>, Instant)> = HashMap::with_capacity(64);
|
||||
let mut timeout = false;
|
||||
let waker = Arc::new(Waker::new(poll.registry(), NOTIFY)?);
|
||||
let stop = waker.clone();
|
||||
let _worker = stop_manager.add_listener("udp_proxy".into(), move || {
|
||||
if let Err(e) = stop.wake() {
|
||||
log::warn!("stop udp_proxy:{:?}", e);
|
||||
}
|
||||
})?;
|
||||
let inner_map: Arc<Mutex<HashMap<SocketAddrV4, (Arc<UdpSocket>, Arc<AtomicCell<Instant>>)>>> =
|
||||
Arc::new(Mutex::new(HashMap::with_capacity(64)));
|
||||
let udp_socket = Arc::new(udp);
|
||||
loop {
|
||||
let mut check = false;
|
||||
if token_map.is_empty() {
|
||||
poll.poll(&mut events, None)?;
|
||||
} else {
|
||||
//所有事件 50分钟超时
|
||||
if let Err(e) = poll.poll(&mut events, Some(Duration::from_secs(50 * 60))) {
|
||||
if e.kind() == io::ErrorKind::TimedOut || e.kind() == io::ErrorKind::WouldBlock {
|
||||
log::warn!(
|
||||
"超时清理所有udp映射 {},token_map={},udp_map={}",
|
||||
e,
|
||||
token_map.len(),
|
||||
udp_map.len()
|
||||
);
|
||||
token_map.clear();
|
||||
udp_map.clear();
|
||||
continue;
|
||||
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
|
||||
{
|
||||
log::warn!("udp proxy {} {:?}", sender_addr, e);
|
||||
}
|
||||
}
|
||||
return Err(e);
|
||||
SocketAddr::V6(_) => {}
|
||||
},
|
||||
Err(e) => {
|
||||
log::warn!("udp代理异常:{:?}", e);
|
||||
}
|
||||
}
|
||||
if stop_manager.is_stop() {
|
||||
return Ok(());
|
||||
}
|
||||
for event in events.iter() {
|
||||
match event.token() {
|
||||
SERVER => server_handle(
|
||||
poll.registry(),
|
||||
&udp,
|
||||
&nat_map,
|
||||
&mut token_map,
|
||||
&mut udp_map,
|
||||
&mut buf,
|
||||
),
|
||||
NOTIFY => {
|
||||
check = true;
|
||||
}
|
||||
token => {
|
||||
if let Err(e) = readable_handle(&udp, &mut token_map, &token, &mut buf) {
|
||||
log::error!("发送目标失败:{:?}", e);
|
||||
if let Some((_, src_addr, _)) = token_map.remove(&token) {
|
||||
udp_map.remove(&src_addr);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async fn udp_proxy0(
|
||||
buf: &[u8],
|
||||
sender_addr: SocketAddrV4,
|
||||
inner_map: &Arc<Mutex<HashMap<SocketAddrV4, (Arc<UdpSocket>, Arc<AtomicCell<Instant>>)>>>,
|
||||
map: &Arc<Mutex<HashMap<SocketAddrV4, SocketAddrV4>>>,
|
||||
udp_socket: &Arc<UdpSocket>,
|
||||
) -> io::Result<()> {
|
||||
let option = inner_map.lock().get(&sender_addr).cloned();
|
||||
if let Some((udp, time)) = option {
|
||||
time.store(Instant::now());
|
||||
udp.send(buf).await?;
|
||||
} else {
|
||||
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?,
|
||||
};
|
||||
peer_udp_socket.connect(dest_addr).await?;
|
||||
peer_udp_socket.send(buf).await?;
|
||||
let peer_udp_socket = Arc::new(peer_udp_socket);
|
||||
let inner_map = inner_map.clone();
|
||||
let time = Arc::new(AtomicCell::new(Instant::now()));
|
||||
inner_map
|
||||
.lock()
|
||||
.insert(sender_addr, (peer_udp_socket.clone(), time.clone()));
|
||||
let udp_socket = udp_socket.clone();
|
||||
let map = map.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 65536];
|
||||
loop {
|
||||
match tokio::time::timeout(
|
||||
Duration::from_secs(600),
|
||||
peer_udp_socket.recv(&mut buf),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(rs) => match rs {
|
||||
Ok(len) => match udp_socket.send_to(&buf[..len], sender_addr).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!("udp proxy {}->{} {:?}", sender_addr, dest_addr, e);
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log::warn!("udp proxy {}->{} {:?}", sender_addr, dest_addr, e);
|
||||
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
if time.load().elapsed() > Duration::from_secs(580) {
|
||||
//超时关闭
|
||||
log::warn!("udp proxy timeout {}->{}", sender_addr, dest_addr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if check {
|
||||
//超时校验
|
||||
if token_map.len() > NAT_MAX / 2 {
|
||||
check_handle(&mut token_map, &mut udp_map, NAT_FAST_TIMEOUT)
|
||||
} else {
|
||||
check_handle(&mut token_map, &mut udp_map, NAT_TIMEOUT)
|
||||
}
|
||||
timeout = false;
|
||||
}
|
||||
if !token_map.is_empty() && !timeout {
|
||||
//注册超时监听
|
||||
timeout = true;
|
||||
let waker = waker.clone();
|
||||
scheduler.timeout(NAT_FAST_TIMEOUT, move |_| {
|
||||
let _ = waker.wake();
|
||||
inner_map.lock().remove(&sender_addr);
|
||||
map.lock().remove(&sender_addr);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_handle(
|
||||
token_map: &mut HashMap<Token, (Rc<UdpSocket>, SocketAddrV4, Instant)>,
|
||||
udp_map: &mut HashMap<SocketAddrV4, (Rc<UdpSocket>, Instant)>,
|
||||
timeout: Duration,
|
||||
) {
|
||||
let mut remove_list = Vec::new();
|
||||
for (token, (_, addr, time)) in token_map.iter() {
|
||||
if time.elapsed() > timeout {
|
||||
if let Some((_, time)) = udp_map.get(addr) {
|
||||
if time.elapsed() > timeout {
|
||||
//映射超时,需要移除
|
||||
remove_list.push(*token);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for token in remove_list {
|
||||
if let Some((_, src_addr, _)) = token_map.remove(&token) {
|
||||
udp_map.remove(&src_addr);
|
||||
log::warn!(
|
||||
"超时清理udp映射 {},token_map={},udp_map={}",
|
||||
src_addr,
|
||||
token_map.len(),
|
||||
udp_map.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn server_handle(
|
||||
registry: &Registry,
|
||||
udp: &UdpSocket,
|
||||
nat_map: &Mutex<HashMap<SocketAddrV4, SocketAddrV4>>,
|
||||
token_map: &mut HashMap<Token, (Rc<UdpSocket>, SocketAddrV4, Instant)>,
|
||||
udp_map: &mut HashMap<SocketAddrV4, (Rc<UdpSocket>, Instant)>,
|
||||
buf: &mut [u8],
|
||||
) {
|
||||
loop {
|
||||
let (len, src_addr) = match udp.recv_from(buf) {
|
||||
Ok((len, src_addr)) => match src_addr {
|
||||
SocketAddr::V4(addr) => (len, addr),
|
||||
SocketAddr::V6(_) => {
|
||||
continue;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
log::error!("接收数据失败:{:?}", e);
|
||||
break;
|
||||
}
|
||||
};
|
||||
if let Some((dest_udp, time)) = udp_map.get_mut(&src_addr) {
|
||||
//发送失败就当丢包了
|
||||
let _ = dest_udp.send(&buf[..len]);
|
||||
*time = Instant::now();
|
||||
} else if let Some(dest_addr) = nat_map.lock().get(&src_addr).cloned() {
|
||||
if token_map.len() >= NAT_MAX {
|
||||
log::error!(
|
||||
"UDP NAT_MAX:src_addr={:?},dest_addr={:?}",
|
||||
src_addr,
|
||||
dest_addr
|
||||
);
|
||||
continue;
|
||||
}
|
||||
match udp_connect(src_addr.port(), dest_addr.into()) {
|
||||
Ok((token_val, mut dest_udp)) => {
|
||||
let token = Token(token_val);
|
||||
if let Err(e) = registry.register(&mut dest_udp, token, Interest::READABLE) {
|
||||
log::error!("register失败:{:?},addr={:?}", e, dest_addr);
|
||||
continue;
|
||||
}
|
||||
let _ = dest_udp.send(&buf[..len]);
|
||||
let dest_udp = Rc::new(dest_udp);
|
||||
token_map.insert(token, (dest_udp.clone(), src_addr, Instant::now()));
|
||||
udp_map.insert(src_addr, (dest_udp, Instant::now()));
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("绑定目标地址失败:{:?}", e);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 得到一个 fd不为SERVER_VAL或者NOTYFY_VAL的socket
|
||||
fn udp_connect(src_port: u16, addr: SocketAddr) -> io::Result<(usize, UdpSocket)> {
|
||||
loop {
|
||||
let udp = if let Ok(udp) =
|
||||
UdpSocket::bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, src_port).into())
|
||||
{
|
||||
udp
|
||||
} else {
|
||||
UdpSocket::bind(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into())?
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let fd = udp.as_raw_socket() as usize;
|
||||
#[cfg(unix)]
|
||||
let fd = udp.as_raw_fd() as usize;
|
||||
if fd == SERVER_VAL || fd == NOTIFY_VAL {
|
||||
continue;
|
||||
}
|
||||
// 只接收目标的数据
|
||||
udp.connect(addr)?;
|
||||
return Ok((fd, udp));
|
||||
}
|
||||
}
|
||||
|
||||
fn readable_handle(
|
||||
udp: &UdpSocket,
|
||||
token_map: &mut HashMap<Token, (Rc<UdpSocket>, SocketAddrV4, Instant)>,
|
||||
token: &Token,
|
||||
buf: &mut [u8],
|
||||
) -> io::Result<()> {
|
||||
if let Some((dest_udp, src_addr, time)) = token_map.get_mut(&token) {
|
||||
loop {
|
||||
let len = match dest_udp.recv(buf) {
|
||||
Ok(rs) => rs,
|
||||
Err(e) => {
|
||||
if e.kind() == io::ErrorKind::WouldBlock {
|
||||
break;
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
if len == 0 {
|
||||
return Err(io::Error::from(io::ErrorKind::UnexpectedEof));
|
||||
}
|
||||
|
||||
let _ = udp.send_to(&buf[..len], (*src_addr).into());
|
||||
}
|
||||
*time = Instant::now();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -8,9 +8,12 @@ pub mod handle;
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
pub mod ip_proxy;
|
||||
pub mod nat;
|
||||
#[cfg(feature = "port_mapping")]
|
||||
pub mod port_mapping;
|
||||
pub mod proto;
|
||||
pub mod protocol;
|
||||
pub mod tun_tap_device;
|
||||
pub mod util;
|
||||
|
||||
pub use handle::callback::*;
|
||||
pub mod compression;
|
||||
|
||||
+68
-3
@@ -1,5 +1,6 @@
|
||||
use anyhow::Context;
|
||||
use std::io;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
|
||||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::ops::Sub;
|
||||
use std::sync::Arc;
|
||||
@@ -7,6 +8,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use rand::Rng;
|
||||
|
||||
use crate::channel::punch::{NatInfo, NatType};
|
||||
use crate::proto::message::PunchNatType;
|
||||
@@ -89,8 +91,9 @@ impl NatTest {
|
||||
udp_ports: Vec<u16>,
|
||||
tcp_port: u16,
|
||||
) -> NatTest {
|
||||
let server = stun_server[0].clone();
|
||||
stun_server.resize(3, server);
|
||||
if stun_server.len() > 5 {
|
||||
stun_server.truncate(5);
|
||||
}
|
||||
let ports = vec![0; udp_ports.len()];
|
||||
let nat_info = NatInfo::new(
|
||||
Vec::new(),
|
||||
@@ -201,4 +204,66 @@ impl NatTest {
|
||||
|
||||
Ok(guard.clone())
|
||||
}
|
||||
pub fn send_data(&self) -> anyhow::Result<(Vec<u8>, SocketAddr)> {
|
||||
let len = self.stun_server.len();
|
||||
let stun_server = if len == 1 {
|
||||
&self.stun_server[0]
|
||||
} else {
|
||||
let index = rand::thread_rng().gen_range(0..self.stun_server.len());
|
||||
&self.stun_server[index]
|
||||
};
|
||||
let addr = stun_server
|
||||
.to_socket_addrs()?
|
||||
.next()
|
||||
.with_context(|| format!("stun error {:?}", stun_server))?;
|
||||
Ok((stun::send_stun_request(), addr))
|
||||
}
|
||||
pub fn recv_data(
|
||||
&self,
|
||||
index: usize,
|
||||
source_addr: SocketAddr,
|
||||
buf: &[u8],
|
||||
) -> anyhow::Result<bool> {
|
||||
if let Some(addr) = stun::recv_stun_response(buf) {
|
||||
if let SocketAddr::V4(addr) = addr {
|
||||
let mut check_fail = true;
|
||||
let source_ip = match source_addr.ip() {
|
||||
IpAddr::V4(ip) => ip,
|
||||
IpAddr::V6(ip) => {
|
||||
if let Some(ip) = ip.to_ipv4_mapped() {
|
||||
ip
|
||||
} else {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
'a: for stun_server in &self.stun_server {
|
||||
for x in stun_server.to_socket_addrs()? {
|
||||
if source_addr.port() == x.port() {
|
||||
if let IpAddr::V4(ip) = x.ip() {
|
||||
if ip == source_ip {
|
||||
check_fail = false;
|
||||
break 'a;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
if check_fail {
|
||||
return Ok(false);
|
||||
}
|
||||
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());
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
|
||||
+93
-59
@@ -1,11 +1,13 @@
|
||||
use std::collections::HashSet;
|
||||
use std::io;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::channel::punch::NatType;
|
||||
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 {
|
||||
@@ -36,26 +38,19 @@ 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")?;
|
||||
udp.set_read_timeout(Some(Duration::from_millis(500)))?;
|
||||
let mut nat_type = NatType::Cone;
|
||||
let mut port_range = 0;
|
||||
let mut min_port = u16::MAX;
|
||||
let mut max_port = 0;
|
||||
let mut hash_set = HashSet::new();
|
||||
let mut pub_addrs = HashSet::new();
|
||||
for x in &stun_servers {
|
||||
match test_nat(&udp, x) {
|
||||
Ok((addr, nat_type_t, ip_list_t, port_range_t)) => {
|
||||
if nat_type_t == NatType::Symmetric {
|
||||
nat_type = NatType::Symmetric;
|
||||
}
|
||||
for x in ip_list_t {
|
||||
hash_set.insert(x);
|
||||
}
|
||||
if port_range < port_range_t {
|
||||
port_range = port_range_t;
|
||||
}
|
||||
pub_addrs.insert(addr);
|
||||
Ok(addr) => {
|
||||
pub_addrs.extend(addr);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("stun {} error {:?} ", x, e);
|
||||
@@ -65,57 +60,58 @@ pub fn stun_test_nat0(stun_servers: Vec<String>) -> io::Result<(NatType, Vec<Ipv
|
||||
if pub_addrs.len() > 1 {
|
||||
nat_type = NatType::Symmetric;
|
||||
}
|
||||
Ok((nat_type, hash_set.into_iter().collect(), port_range))
|
||||
for addr in &pub_addrs {
|
||||
if let SocketAddr::V4(addr) = addr {
|
||||
hash_set.insert(*addr.ip());
|
||||
if min_port > addr.port() {
|
||||
min_port = addr.port()
|
||||
}
|
||||
if max_port < addr.port() {
|
||||
max_port = addr.port()
|
||||
}
|
||||
}
|
||||
}
|
||||
if hash_set.is_empty() {
|
||||
Ok((nat_type, vec![], 0))
|
||||
} else {
|
||||
Ok((
|
||||
nat_type,
|
||||
hash_set.into_iter().collect(),
|
||||
max_port - min_port,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn test_nat(
|
||||
udp: &UdpSocket,
|
||||
stun_server: &String,
|
||||
) -> io::Result<(SocketAddr, NatType, Vec<Ipv4Addr>, u16)> {
|
||||
fn test_nat(udp: &UdpSocket, stun_server: &String) -> io::Result<HashSet<SocketAddr>> {
|
||||
udp.connect(stun_server)?;
|
||||
let mut port_range = 0;
|
||||
let mut hash_set = HashSet::new();
|
||||
let mut nat_type = NatType::Cone;
|
||||
// 随便搞个当id
|
||||
let tid = stun_server.as_ptr() as u128;
|
||||
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)?;
|
||||
match mapped_addr1.ip() {
|
||||
IpAddr::V4(ip) => {
|
||||
hash_set.insert(ip);
|
||||
}
|
||||
IpAddr::V6(_) => {}
|
||||
if mapped_addr1.is_ipv4() {
|
||||
addr.insert(mapped_addr1);
|
||||
}
|
||||
if udp.connect(changed_addr1).is_ok() {
|
||||
match test_nat_(&udp, false, false, tid + 1) {
|
||||
Ok((mapped_addr2, _)) => {
|
||||
match mapped_addr2.ip() {
|
||||
IpAddr::V4(ip) => {
|
||||
hash_set.insert(ip);
|
||||
if mapped_addr1 != mapped_addr2 {
|
||||
nat_type = NatType::Symmetric;
|
||||
}
|
||||
if let Some(changed_addr1) = changed_addr1 {
|
||||
if udp.connect(changed_addr1).is_ok() {
|
||||
match test_nat_(&udp, false, false, tid + 1) {
|
||||
Ok((mapped_addr2, _)) => {
|
||||
if mapped_addr2.is_ipv4() {
|
||||
addr.insert(mapped_addr1);
|
||||
}
|
||||
IpAddr::V6(_) => {}
|
||||
}
|
||||
port_range = mapped_addr2.port().abs_diff(mapped_addr1.port());
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("stun {} error {:?} ", stun_server, e);
|
||||
Err(e) => {
|
||||
log::warn!("stun {} error {:?} ", stun_server, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
log::warn!(
|
||||
"stun {} mapped_addr {:?} nat_type {:?}",
|
||||
log::info!(
|
||||
"stun {} mapped_addr {:?} changed_addr {:?}",
|
||||
stun_server,
|
||||
mapped_addr1,
|
||||
nat_type
|
||||
addr,
|
||||
changed_addr1,
|
||||
);
|
||||
Ok((
|
||||
mapped_addr1,
|
||||
nat_type,
|
||||
hash_set.into_iter().collect(),
|
||||
port_range,
|
||||
))
|
||||
|
||||
Ok(addr)
|
||||
}
|
||||
|
||||
fn test_nat_(
|
||||
@@ -123,17 +119,16 @@ fn test_nat_(
|
||||
change_ip: bool,
|
||||
change_port: bool,
|
||||
tid: u128,
|
||||
) -> io::Result<(SocketAddr, SocketAddr)> {
|
||||
) -> io::Result<(SocketAddr, Option<SocketAddr>)> {
|
||||
for _ in 0..2 {
|
||||
let mut buf = [0u8; 28];
|
||||
let mut msg = stun_format::MsgBuilder::from(buf.as_mut_slice());
|
||||
msg.typ(stun_format::MsgType::BindingRequest).unwrap();
|
||||
msg.tid(tid).unwrap();
|
||||
msg.typ(stun_format::MsgType::BindingRequest);
|
||||
msg.tid(tid);
|
||||
msg.add_attr(Attr::ChangeRequest {
|
||||
change_ip,
|
||||
change_port,
|
||||
})
|
||||
.unwrap();
|
||||
});
|
||||
udp.send(msg.as_bytes())?;
|
||||
let mut buf = [0; 10240];
|
||||
let (len, _addr) = match udp.recv_from(&mut buf) {
|
||||
@@ -166,11 +161,11 @@ fn test_nat_(
|
||||
_ => {}
|
||||
}
|
||||
if changed_addr.is_some() && mapped_addr.is_some() {
|
||||
return Ok((mapped_addr.unwrap(), changed_addr.unwrap()));
|
||||
return Ok((mapped_addr.unwrap(), changed_addr));
|
||||
}
|
||||
}
|
||||
if let Some(addr) = mapped_addr {
|
||||
return Ok((addr, changed_addr.unwrap_or(addr)));
|
||||
return Ok((addr, changed_addr));
|
||||
}
|
||||
}
|
||||
Err(io::Error::new(io::ErrorKind::Other, "stun response err"))
|
||||
@@ -186,3 +181,42 @@ fn stun_addr(addr: stun_format::SocketAddr) -> SocketAddr {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const TAG: u128 = 1827549368 << 64;
|
||||
|
||||
pub fn send_stun_request() -> Vec<u8> {
|
||||
let mut buf = [0u8; 28];
|
||||
let mut msg = stun_format::MsgBuilder::from(buf.as_mut_slice());
|
||||
msg.typ(stun_format::MsgType::BindingRequest);
|
||||
let id = rand::thread_rng().next_u64() as u128;
|
||||
msg.tid(id | TAG);
|
||||
msg.add_attr(Attr::ChangeRequest {
|
||||
change_ip: false,
|
||||
change_port: false,
|
||||
});
|
||||
msg.as_bytes().to_vec()
|
||||
}
|
||||
|
||||
pub fn recv_stun_response(buf: &[u8]) -> Option<SocketAddr> {
|
||||
if buf[0] != 0x01 && buf[1] != 0x01 {
|
||||
return None;
|
||||
}
|
||||
let msg = stun_format::Msg::from(buf);
|
||||
if let Some(tid) = msg.tid() {
|
||||
if tid & TAG != TAG {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for x in msg.attrs_iter() {
|
||||
match x {
|
||||
Attr::MappedAddress(addr) => {
|
||||
return Some(stun_addr(addr));
|
||||
}
|
||||
Attr::XorMappedAddress(addr) => {
|
||||
return Some(stun_addr(addr));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::str::FromStr;
|
||||
use std::thread;
|
||||
|
||||
use anyhow::Context;
|
||||
|
||||
use crate::util::StopManager;
|
||||
|
||||
mod tcp_mapping;
|
||||
|
||||
mod udp_mapping;
|
||||
|
||||
pub fn convert(vec: Vec<String>) -> anyhow::Result<Vec<(bool, SocketAddr, String)>> {
|
||||
let mut rs = Vec::with_capacity(vec.len());
|
||||
for x in vec {
|
||||
let string = x.trim().to_lowercase();
|
||||
if let Some(udp_mapping) = string.strip_prefix("udp:") {
|
||||
let mut split = udp_mapping.split("->");
|
||||
let bind_addr = split.next().with_context(|| {
|
||||
format!(
|
||||
"udp_mapping error {:?},eg: udp:127.0.0.1:80->10.26.0.10:8080",
|
||||
x
|
||||
)
|
||||
})?;
|
||||
let bind_addr = SocketAddr::from_str(bind_addr)
|
||||
.with_context(|| format!("udp_mapping error {}", bind_addr))?;
|
||||
let dest = split.next().with_context(|| {
|
||||
format!(
|
||||
"udp_mapping error {:?},eg: udp:127.0.0.1:80->10.26.0.10:8080",
|
||||
x
|
||||
)
|
||||
})?;
|
||||
rs.push((false, bind_addr, dest.to_string()));
|
||||
continue;
|
||||
}
|
||||
if let Some(tcp_mapping) = string.strip_prefix("tcp:") {
|
||||
let mut split = tcp_mapping.split("->");
|
||||
let bind_addr = split.next().with_context(|| {
|
||||
format!(
|
||||
"tcp_mapping error {:?},eg: tcp:127.0.0.1:80->10.26.0.10:8080",
|
||||
x
|
||||
)
|
||||
})?;
|
||||
let bind_addr = SocketAddr::from_str(bind_addr)
|
||||
.with_context(|| format!("udp_mapping error {}", bind_addr))?;
|
||||
let dest = split.next().with_context(|| {
|
||||
format!(
|
||||
"tcp_mapping error {:?},eg: tcp:127.0.0.1:80->10.26.0.10:8080",
|
||||
x
|
||||
)
|
||||
})?;
|
||||
rs.push((true, bind_addr, dest.to_string()));
|
||||
continue;
|
||||
}
|
||||
Err(anyhow::anyhow!(
|
||||
"port_mapping error {:?},eg: tcp:127.0.0.1:80->10.26.0.10:8080",
|
||||
x
|
||||
))?;
|
||||
}
|
||||
Ok(rs)
|
||||
}
|
||||
pub fn start_port_mapping(
|
||||
stop_manager: StopManager,
|
||||
vec: Vec<(bool, SocketAddr, String)>,
|
||||
) -> anyhow::Result<()> {
|
||||
if vec.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.thread_name("portMapping")
|
||||
.build()?;
|
||||
runtime.block_on(start_port_mapping0(vec))?;
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel::<()>();
|
||||
let worker = stop_manager.add_listener("portMapping".into(), move || {
|
||||
let _ = sender.send(());
|
||||
})?;
|
||||
thread::Builder::new()
|
||||
.name("portMapping".into())
|
||||
.spawn(move || {
|
||||
runtime.block_on(async {
|
||||
let _ = receiver.await;
|
||||
});
|
||||
runtime.shutdown_background();
|
||||
drop(worker);
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn start_port_mapping0(vec: Vec<(bool, SocketAddr, String)>) -> anyhow::Result<()> {
|
||||
for (is_tcp, bind_addr, destination) in vec {
|
||||
if is_tcp {
|
||||
tcp_mapping::tcp_mapping(bind_addr, destination).await?;
|
||||
} else {
|
||||
udp_mapping::udp_mapping(bind_addr, destination).await?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
use anyhow::Context;
|
||||
use std::net::SocketAddr;
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
|
||||
pub async fn tcp_mapping(bind_addr: SocketAddr, destination: String) -> anyhow::Result<()> {
|
||||
let tcp_listener = TcpListener::bind(bind_addr)
|
||||
.await
|
||||
.with_context(|| format!("TCP binding {:?} failed", bind_addr))?;
|
||||
tokio::spawn(tcp_mapping_(bind_addr, tcp_listener, destination));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn tcp_mapping_(
|
||||
bind_addr: SocketAddr,
|
||||
tcp_listener: TcpListener,
|
||||
destination: String,
|
||||
) -> anyhow::Result<()> {
|
||||
loop {
|
||||
let (tcp_stream, _) = tcp_listener.accept().await?;
|
||||
|
||||
let destination = destination.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = copy(tcp_stream, &destination).await {
|
||||
log::warn!("tcp port mapping {}->{} {:?}", bind_addr, destination, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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))?;
|
||||
let _ = source_tcp.set_nodelay(true);
|
||||
let _ = dest_tcp.set_nodelay(true);
|
||||
|
||||
let destination = dest_tcp.peer_addr()?;
|
||||
let (mut client_read, mut client_write) = source_tcp.into_split();
|
||||
let (mut server_read, mut server_write) = dest_tcp.into_split();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = tokio::io::copy(&mut client_read, &mut server_write).await {
|
||||
log::warn!("client tcp proxy ->{:},{:?}", destination, e);
|
||||
}
|
||||
});
|
||||
if let Err(e) = tokio::io::copy(&mut server_read, &mut client_write).await {
|
||||
log::warn!("server tcp proxy ->{:?},{:?}", destination, e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use anyhow::Context;
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use parking_lot::Mutex;
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
pub async fn udp_mapping(bind_addr: SocketAddr, destination: String) -> anyhow::Result<()> {
|
||||
let udp = UdpSocket::bind(bind_addr)
|
||||
.await
|
||||
.with_context(|| format!("port proxy UDP binding {:?} failed", bind_addr))?;
|
||||
let udp = Arc::new(udp);
|
||||
|
||||
let inner_map: Arc<Mutex<HashMap<SocketAddr, (Arc<UdpSocket>, Arc<AtomicCell<Instant>>)>>> =
|
||||
Arc::new(Mutex::new(HashMap::with_capacity(64)));
|
||||
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0; 65536];
|
||||
loop {
|
||||
match udp.recv_from(&mut buf).await {
|
||||
Ok((len, src_addr)) => {
|
||||
if let Err(e) =
|
||||
udp_mapping0(&buf[..len], src_addr, &inner_map, &udp, &destination).await
|
||||
{
|
||||
log::warn!("udp port mapping {}->{} {:?}", src_addr, destination, e);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("port proxy UDP {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn udp_mapping0(
|
||||
buf: &[u8],
|
||||
src_addr: SocketAddr,
|
||||
inner_map: &Arc<Mutex<HashMap<SocketAddr, (Arc<UdpSocket>, Arc<AtomicCell<Instant>>)>>>,
|
||||
udp_socket: &Arc<UdpSocket>,
|
||||
destination: &String,
|
||||
) -> anyhow::Result<()> {
|
||||
let option = inner_map.lock().get(&src_addr).cloned();
|
||||
if let Some((udp, time)) = option {
|
||||
time.store(Instant::now());
|
||||
udp.send(buf).await?;
|
||||
} else {
|
||||
let dest_udp = UdpSocket::bind("0.0.0.0:0").await?;
|
||||
dest_udp.connect(destination).await?;
|
||||
dest_udp.send(buf).await?;
|
||||
let destination_addr = dest_udp.peer_addr()?;
|
||||
let udp_socket = udp_socket.clone();
|
||||
let inner_map = inner_map.clone();
|
||||
let dest_udp = Arc::new(dest_udp);
|
||||
let time = Arc::new(AtomicCell::new(Instant::now()));
|
||||
inner_map
|
||||
.lock()
|
||||
.insert(src_addr, (dest_udp.clone(), time.clone()));
|
||||
tokio::spawn(async move {
|
||||
let mut buf = [0u8; 65536];
|
||||
loop {
|
||||
match tokio::time::timeout(Duration::from_secs(600), dest_udp.recv(&mut buf)).await
|
||||
{
|
||||
Ok(rs) => match rs {
|
||||
Ok(len) => match udp_socket.send_to(&buf[..len], src_addr).await {
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"udp port mapping {}->{} {:?}",
|
||||
src_addr,
|
||||
destination_addr,
|
||||
e
|
||||
);
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"udp port mapping {}->{} {:?}",
|
||||
src_addr,
|
||||
destination_addr,
|
||||
e
|
||||
);
|
||||
break;
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
if time.load().elapsed() > Duration::from_secs(580) {
|
||||
//超时关闭
|
||||
log::warn!(
|
||||
"udp port mapping timeout {}->{} ",
|
||||
src_addr,
|
||||
destination_addr
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
inner_map.lock().remove(&src_addr);
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -253,6 +253,85 @@ impl<B: AsRef<[u8]> + AsMut<[u8]>> AesCbcSecretBody<B> {
|
||||
&mut self.buffer.as_mut()[..end]
|
||||
}
|
||||
}
|
||||
/* ChaCah20加密数据体
|
||||
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
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 数据体 |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| finger(32) |
|
||||
| finger(32) |
|
||||
| finger(32) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
|
||||
注:finger用于快速校验数据是否被修改,上层可使用token、协议头参与计算finger,
|
||||
确保服务端和客户端都能感知修改(服务端不能解密也能校验指纹)
|
||||
*/
|
||||
pub struct ChaCah20SecretBody<B> {
|
||||
buffer: B,
|
||||
exist_finger: bool,
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]>> ChaCah20SecretBody<B> {
|
||||
pub fn new(buffer: B, exist_finger: bool) -> io::Result<ChaCah20SecretBody<B>> {
|
||||
let len = buffer.as_ref().len();
|
||||
let min_len = if exist_finger { 12 } else { 0 };
|
||||
// 不能大于udp最大载荷长度
|
||||
if len < min_len || len > 65535 - 20 - 8 - 12 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"ChaCah20SecretBody length overflow",
|
||||
));
|
||||
}
|
||||
Ok(ChaCah20SecretBody {
|
||||
buffer,
|
||||
exist_finger,
|
||||
})
|
||||
}
|
||||
pub fn en_body(&self) -> &[u8] {
|
||||
let mut end = self.buffer.as_ref().len();
|
||||
if self.exist_finger {
|
||||
end -= 12;
|
||||
}
|
||||
&self.buffer.as_ref()[..end]
|
||||
}
|
||||
pub fn finger(&self) -> &[u8] {
|
||||
if self.exist_finger {
|
||||
let end = self.buffer.as_ref().len();
|
||||
&self.buffer.as_ref()[end - 12..end]
|
||||
} else {
|
||||
&[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]> + AsMut<[u8]>> ChaCah20SecretBody<B> {
|
||||
pub fn set_finger(&mut self, finger: &[u8]) -> io::Result<()> {
|
||||
if self.exist_finger {
|
||||
if finger.len() != 12 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"finger.len != 12",
|
||||
));
|
||||
}
|
||||
let end = self.buffer.as_ref().len();
|
||||
self.buffer.as_mut()[end - 12..end].copy_from_slice(finger);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"cbc not exist finger",
|
||||
))
|
||||
}
|
||||
}
|
||||
pub fn en_body_mut(&mut self) -> &mut [u8] {
|
||||
let mut end = self.buffer.as_ref().len();
|
||||
if self.exist_finger {
|
||||
end -= 12;
|
||||
}
|
||||
&mut self.buffer.as_mut()[..end]
|
||||
}
|
||||
}
|
||||
|
||||
/* rsa加密数据体
|
||||
0 15 31
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
/* 扩展协议
|
||||
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
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 扩展数据(n) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| 扩展数据(n) | type(8) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
注:扩展数据的长度由type决定
|
||||
*/
|
||||
|
||||
use anyhow::anyhow;
|
||||
use std::io;
|
||||
|
||||
use crate::protocol::NetPacket;
|
||||
|
||||
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
|
||||
pub enum ExtensionTailType {
|
||||
Compression,
|
||||
Unknown(u8),
|
||||
}
|
||||
|
||||
impl From<u8> for ExtensionTailType {
|
||||
fn from(value: u8) -> Self {
|
||||
if value == 0 {
|
||||
ExtensionTailType::Compression
|
||||
} else {
|
||||
ExtensionTailType::Unknown(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum ExtensionTailPacket<B> {
|
||||
Compression(CompressionExtensionTail<B>),
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]> + AsMut<[u8]>> NetPacket<B> {
|
||||
/// 分离尾部数据
|
||||
pub fn split_tail_packet(&mut self) -> anyhow::Result<ExtensionTailPacket<&[u8]>> {
|
||||
if self.is_extension() {
|
||||
let payload = self.payload();
|
||||
if let Some(v) = payload.last() {
|
||||
return match ExtensionTailType::from(*v) {
|
||||
ExtensionTailType::Compression => {
|
||||
let data_len = self.data_len - 4;
|
||||
self.set_data_len(data_len)?;
|
||||
self.set_extension_flag(false);
|
||||
Ok(ExtensionTailPacket::Compression(
|
||||
CompressionExtensionTail::new(
|
||||
&self.raw_buffer()[data_len..data_len + 4],
|
||||
),
|
||||
))
|
||||
}
|
||||
ExtensionTailType::Unknown(e) => Err(anyhow!("unknown extension {}", e)),
|
||||
};
|
||||
}
|
||||
}
|
||||
Err(anyhow!("not extension"))
|
||||
}
|
||||
/// 追加压缩扩展
|
||||
pub fn append_compression_extension_tail(
|
||||
&mut self,
|
||||
) -> io::Result<CompressionExtensionTail<&mut [u8]>> {
|
||||
let len = self.data_len;
|
||||
//增加数据长度
|
||||
self.set_data_len(self.data_len + 4)?;
|
||||
self.set_extension_flag(true);
|
||||
let mut tail = CompressionExtensionTail::new(&mut self.buffer_mut()[len..]);
|
||||
tail.init();
|
||||
return Ok(tail);
|
||||
}
|
||||
}
|
||||
|
||||
/* 扩展协议
|
||||
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
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
| algorithm(8) | | type(8) |
|
||||
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|
||||
注:扩展数据的长度由type决定
|
||||
*/
|
||||
/// 压缩扩展
|
||||
pub struct CompressionExtensionTail<B> {
|
||||
buffer: B,
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]>> CompressionExtensionTail<B> {
|
||||
pub fn new(buffer: B) -> CompressionExtensionTail<B> {
|
||||
assert_eq!(buffer.as_ref().len(), 4);
|
||||
CompressionExtensionTail { buffer }
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]>> CompressionExtensionTail<B> {
|
||||
pub fn algorithm(&self) -> CompressionAlgorithm {
|
||||
self.buffer.as_ref()[0].into()
|
||||
}
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]> + AsMut<[u8]>> CompressionExtensionTail<B> {
|
||||
pub fn init(&mut self) {
|
||||
self.buffer.as_mut().fill(0);
|
||||
}
|
||||
pub fn set_algorithm(&mut self, algorithm: CompressionAlgorithm) {
|
||||
self.buffer.as_mut()[0] = algorithm.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
|
||||
pub enum CompressionAlgorithm {
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
Lz4,
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
Zstd,
|
||||
Unknown(u8),
|
||||
}
|
||||
|
||||
impl From<u8> for CompressionAlgorithm {
|
||||
fn from(value: u8) -> Self {
|
||||
match value {
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
1 => CompressionAlgorithm::Lz4,
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
2 => CompressionAlgorithm::Zstd,
|
||||
v => CompressionAlgorithm::Unknown(v),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CompressionAlgorithm> for u8 {
|
||||
fn from(value: CompressionAlgorithm) -> Self {
|
||||
match value {
|
||||
#[cfg(feature = "lz4_compress")]
|
||||
CompressionAlgorithm::Lz4 => 1,
|
||||
#[cfg(feature = "zstd_compress")]
|
||||
CompressionAlgorithm::Zstd => 2,
|
||||
CompressionAlgorithm::Unknown(val) => val,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ pub const HEAD_LEN: usize = 12;
|
||||
pub mod body;
|
||||
pub mod control_packet;
|
||||
pub mod error_packet;
|
||||
pub mod extension;
|
||||
pub mod ip_turn_packet;
|
||||
pub mod other_turn_packet;
|
||||
pub mod service_packet;
|
||||
@@ -101,6 +102,10 @@ pub struct NetPacket<B> {
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]>> NetPacket<B> {
|
||||
pub fn unchecked(buffer: B) -> Self {
|
||||
let data_len = buffer.as_ref().len();
|
||||
Self { data_len, buffer }
|
||||
}
|
||||
pub fn new(buffer: B) -> io::Result<NetPacket<B>> {
|
||||
let data_len = buffer.as_ref().len();
|
||||
Self::new0(data_len, buffer)
|
||||
@@ -158,6 +163,10 @@ impl<B: AsRef<[u8]>> NetPacket<B> {
|
||||
pub fn is_gateway(&self) -> bool {
|
||||
self.buffer.as_ref()[0] & 0x40 == 0x40
|
||||
}
|
||||
/// 扩展协议
|
||||
pub fn is_extension(&self) -> bool {
|
||||
self.buffer.as_ref()[0] & 0x20 == 0x20
|
||||
}
|
||||
pub fn version(&self) -> Version {
|
||||
Version::from(self.buffer.as_ref()[0] & 0x0F)
|
||||
}
|
||||
@@ -190,6 +199,9 @@ impl<B: AsRef<[u8]>> NetPacket<B> {
|
||||
}
|
||||
|
||||
impl<B: AsRef<[u8]> + AsMut<[u8]>> NetPacket<B> {
|
||||
pub fn head_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.buffer.as_mut()[..12]
|
||||
}
|
||||
pub fn buffer_mut(&mut self) -> &mut [u8] {
|
||||
&mut self.buffer.as_mut()[..self.data_len]
|
||||
}
|
||||
@@ -208,6 +220,13 @@ impl<B: AsRef<[u8]> + AsMut<[u8]>> NetPacket<B> {
|
||||
self.buffer.as_mut()[0] = self.buffer.as_ref()[0] & 0xBF
|
||||
};
|
||||
}
|
||||
pub fn set_extension_flag(&mut self, is_extension: bool) {
|
||||
if is_extension {
|
||||
self.buffer.as_mut()[0] = self.buffer.as_ref()[0] | 0x20
|
||||
} else {
|
||||
self.buffer.as_mut()[0] = self.buffer.as_ref()[0] & 0xDF
|
||||
};
|
||||
}
|
||||
pub fn set_default_version(&mut self) {
|
||||
let v: u8 = Version::V2.into();
|
||||
self.buffer.as_mut()[0] = (self.buffer.as_ref()[0] & 0xF0) | (0x0F & v);
|
||||
@@ -264,6 +283,10 @@ impl<B: AsRef<[u8]> + AsMut<[u8]>> NetPacket<B> {
|
||||
self.data_len = data_len;
|
||||
Ok(())
|
||||
}
|
||||
pub fn set_payload_len(&mut self, payload_len: usize) -> io::Result<()> {
|
||||
let data_len = HEAD_LEN + payload_len;
|
||||
self.set_data_len(data_len)
|
||||
}
|
||||
pub fn set_data_len_max(&mut self) {
|
||||
self.data_len = self.buffer.as_ref().len();
|
||||
}
|
||||
|
||||
@@ -5,12 +5,12 @@ use tun::Device;
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
const DEFAULT_TUN_NAME: &str = "vnt-tun";
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
const DEFAULT_TAP_NAME: &str = "vnt-tap";
|
||||
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
pub fn create_device(config: &crate::core::Config) -> io::Result<Arc<Device>> {
|
||||
#[cfg(any(target_os = "windows", target_os = "linux"))]
|
||||
#[cfg(target_os = "windows")]
|
||||
let default_name: &str = if config.tap {
|
||||
DEFAULT_TAP_NAME
|
||||
} else {
|
||||
@@ -21,11 +21,11 @@ pub fn create_device(config: &crate::core::Config) -> io::Result<Arc<Device>> {
|
||||
let device_name = config
|
||||
.device_name
|
||||
.clone()
|
||||
.unwrap_or(default_name.to_string());
|
||||
if &device_name == default_name {
|
||||
delete_device(default_name);
|
||||
.unwrap_or(DEFAULT_TUN_NAME.to_string());
|
||||
if &device_name == DEFAULT_TUN_NAME {
|
||||
delete_device(DEFAULT_TUN_NAME);
|
||||
}
|
||||
Arc::new(Device::new(Some(device_name), config.tap)?)
|
||||
Arc::new(Device::new(Some(device_name))?)
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let device = Arc::new(Device::new(config.device_name.clone())?);
|
||||
|
||||
@@ -8,8 +8,10 @@ use tun::Device;
|
||||
|
||||
use crate::channel::context::ChannelContext;
|
||||
use crate::cipher::Cipher;
|
||||
use crate::compression::Compressor;
|
||||
use crate::external_route::ExternalRoute;
|
||||
use crate::handle::{CurrentDeviceInfo, PeerDeviceInfo};
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
use crate::ip_proxy::IpProxyMap;
|
||||
use crate::util::{SingleU64Adder, StopManager};
|
||||
#[cfg(any(target_os = "windows", target_os = "linux", target_os = "macos"))]
|
||||
@@ -26,7 +28,7 @@ impl DeviceAdapter {
|
||||
#[cfg(target_os = "android")]
|
||||
pub fn new(tun_device_helper: TunDeviceHelper) -> Self {
|
||||
Self {
|
||||
tun: Arc::new(Mutex::new(None)),
|
||||
tun: Arc::new(AtomicCell::new(-1 as _)),
|
||||
tun_device_helper,
|
||||
}
|
||||
}
|
||||
@@ -43,22 +45,19 @@ impl std::ops::Deref for DeviceAdapter {
|
||||
#[cfg(target_os = "android")]
|
||||
#[derive(Clone)]
|
||||
pub struct DeviceAdapter {
|
||||
tun: Arc<Mutex<Option<Arc<Device>>>>,
|
||||
tun: Arc<AtomicCell<std::os::fd::RawFd>>,
|
||||
tun_device_helper: TunDeviceHelper,
|
||||
}
|
||||
#[cfg(target_os = "android")]
|
||||
impl DeviceAdapter {
|
||||
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
|
||||
if let Some(device) = self.tun.lock().as_ref() {
|
||||
use tun::device::IFace;
|
||||
device.write(buf)
|
||||
} else {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "not tun device"))
|
||||
}
|
||||
let fd = self.tun.load();
|
||||
tun::Fd(fd).write(buf)
|
||||
}
|
||||
pub fn start(&self, device: Arc<Device>) -> io::Result<()> {
|
||||
self.tun_device_helper.start(device.clone())?;
|
||||
self.tun.lock().replace(device);
|
||||
pub fn start(&self, fd: std::os::fd::RawFd) -> io::Result<()> {
|
||||
//安卓端fd是由外部释放的,所以这里这么搞免得加锁
|
||||
self.tun_device_helper.start(Arc::new(Device::new(fd)?))?;
|
||||
self.tun.store(fd);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -80,6 +79,7 @@ struct TunDeviceHelperInner {
|
||||
parallel: usize,
|
||||
up_counter: SingleU64Adder,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
compressor: Compressor,
|
||||
}
|
||||
|
||||
impl TunDeviceHelper {
|
||||
@@ -94,6 +94,7 @@ impl TunDeviceHelper {
|
||||
parallel: usize,
|
||||
up_counter: SingleU64Adder,
|
||||
device_list: Arc<Mutex<(u16, Vec<PeerDeviceInfo>)>>,
|
||||
compressor: Compressor,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: Arc::new(AtomicCell::new(Some(TunDeviceHelperInner {
|
||||
@@ -101,12 +102,14 @@ impl TunDeviceHelper {
|
||||
context,
|
||||
current_device,
|
||||
ip_route,
|
||||
#[cfg(feature = "ip_proxy")]
|
||||
ip_proxy_map,
|
||||
client_cipher,
|
||||
server_cipher,
|
||||
parallel,
|
||||
up_counter,
|
||||
device_list,
|
||||
compressor,
|
||||
}))),
|
||||
}
|
||||
}
|
||||
@@ -125,6 +128,7 @@ impl TunDeviceHelper {
|
||||
inner.parallel,
|
||||
inner.up_counter,
|
||||
inner.device_list,
|
||||
inner.compressor,
|
||||
)?;
|
||||
Ok(())
|
||||
} else {
|
||||
|
||||
+27
-13
@@ -41,9 +41,10 @@ pub fn address_choose(addrs: Vec<SocketAddr>) -> anyhow::Result<SocketAddr> {
|
||||
/// 后续实现选择延迟最低的可用地址,需要服务端配合
|
||||
/// 现在是选择第一个地址,优先ipv6
|
||||
fn address_choose0(addrs: Vec<SocketAddr>) -> anyhow::Result<SocketAddr> {
|
||||
let v4: Vec<SocketAddr> = addrs.iter().filter(|v| v.is_ipv4()).map(|v| *v).collect();
|
||||
let v6: Vec<SocketAddr> = addrs.iter().filter(|v| v.is_ipv6()).map(|v| *v).collect();
|
||||
let v4: Vec<SocketAddr> = addrs.iter().filter(|v| v.is_ipv4()).copied().collect();
|
||||
let v6: Vec<SocketAddr> = addrs.iter().filter(|v| v.is_ipv6()).copied().collect();
|
||||
let check_addr = |addrs: &Vec<SocketAddr>| -> anyhow::Result<SocketAddr> {
|
||||
let mut err = Vec::new();
|
||||
if !addrs.is_empty() {
|
||||
let udp = if addrs[0].is_ipv6() {
|
||||
UdpSocket::bind("[::]:0")?
|
||||
@@ -51,12 +52,14 @@ fn address_choose0(addrs: Vec<SocketAddr>) -> anyhow::Result<SocketAddr> {
|
||||
UdpSocket::bind("0.0.0.0:0")?
|
||||
};
|
||||
for addr in addrs {
|
||||
if udp.connect(addr).is_ok() {
|
||||
if let Err(e) = udp.connect(addr) {
|
||||
err.push((*addr, e));
|
||||
} else {
|
||||
return Ok(*addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(anyhow::anyhow!("Unable to connect to address {:?}", addrs))
|
||||
Err(anyhow::anyhow!("Unable to connect to address {:?}", err))
|
||||
};
|
||||
if v6.is_empty() {
|
||||
return check_addr(&v4);
|
||||
@@ -78,9 +81,7 @@ pub fn dns_query_all(
|
||||
mut name_servers: Vec<String>,
|
||||
) -> anyhow::Result<Vec<SocketAddr>> {
|
||||
match SocketAddr::from_str(domain) {
|
||||
Ok(addr) => {
|
||||
return Ok(vec![addr]);
|
||||
}
|
||||
Ok(addr) => Ok(vec![addr]),
|
||||
Err(_) => {
|
||||
let txt_domain = domain
|
||||
.to_lowercase()
|
||||
@@ -94,7 +95,6 @@ pub fn dns_query_all(
|
||||
return Ok(domain
|
||||
.to_socket_addrs()
|
||||
.with_context(|| format!("DNS query failed {:?}", domain))?
|
||||
.into_iter()
|
||||
.collect());
|
||||
}
|
||||
}
|
||||
@@ -102,10 +102,24 @@ 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() {
|
||||
return txt_dns(domain, name_server);
|
||||
match txt_dns(domain, name_server) {
|
||||
Ok(addr) => {
|
||||
if !addr.is_empty() {
|
||||
return Ok(addr);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(err) = &mut err {
|
||||
*err = anyhow::anyhow!("{} {}", err, e);
|
||||
} else {
|
||||
err.replace(anyhow::anyhow!("{}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let end_index = domain
|
||||
.rfind(":")
|
||||
.rfind(':')
|
||||
.with_context(|| format!("{:?} not port", domain))?;
|
||||
let host = &domain[..end_index];
|
||||
let port = u16::from_str(&domain[end_index + 1..])
|
||||
@@ -205,7 +219,7 @@ fn query<'a>(
|
||||
domain
|
||||
));
|
||||
}
|
||||
if pkt.answers.len() == 0 {
|
||||
if pkt.answers.is_empty() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"No records received DNS {:?} domain {:?}",
|
||||
name_server,
|
||||
@@ -226,8 +240,8 @@ pub fn txt_dns(domain: &str, name_server: String) -> anyhow::Result<Vec<SocketAd
|
||||
if let RData::TXT(txt) = record.data {
|
||||
for x in txt.iter() {
|
||||
let txt = std::str::from_utf8(x).context("record type txt is not string")?;
|
||||
let addr = SocketAddr::from_str(&txt.to_string())
|
||||
.context("record type txt is not SocketAddr")?;
|
||||
let addr =
|
||||
SocketAddr::from_str(txt).context("record type txt is not SocketAddr")?;
|
||||
rs.push(addr);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
mod notify;
|
||||
mod result_convert;
|
||||
pub use result_convert::io_convert;
|
||||
mod scheduler;
|
||||
pub use notify::StopManager;
|
||||
pub use scheduler::Scheduler;
|
||||
|
||||
+23
-9
@@ -1,8 +1,10 @@
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::thread::Thread;
|
||||
use std::{io, thread};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::anyhow;
|
||||
use parking_lot::Mutex;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -19,7 +21,7 @@ impl StopManager {
|
||||
inner: Arc::new(StopManagerInner::new(f)),
|
||||
}
|
||||
}
|
||||
pub fn add_listener<F>(&self, name: String, f: F) -> io::Result<Worker>
|
||||
pub fn add_listener<F>(&self, name: String, f: F) -> anyhow::Result<Worker>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
@@ -31,6 +33,9 @@ impl StopManager {
|
||||
pub fn wait(&self) {
|
||||
self.inner.wait();
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -57,23 +62,20 @@ impl StopManagerInner {
|
||||
stop_call: Mutex::new(Some(Box::new(f))),
|
||||
}
|
||||
}
|
||||
fn add_listener<F>(self: &Arc<Self>, name: String, f: F) -> io::Result<Worker>
|
||||
fn add_listener<F>(self: &Arc<Self>, name: String, f: F) -> anyhow::Result<Worker>
|
||||
where
|
||||
F: FnOnce() + Send + 'static,
|
||||
{
|
||||
if name.is_empty() {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "name cannot be empty"));
|
||||
return Err(anyhow!("name cannot be empty"));
|
||||
}
|
||||
let mut guard = self.listeners.lock();
|
||||
if guard.0 {
|
||||
return Err(io::Error::new(io::ErrorKind::Other, "stopped"));
|
||||
return Err(anyhow!("stopped"));
|
||||
}
|
||||
for (n, _) in &guard.1 {
|
||||
if &name == n {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("stop add_listener {:?} name already exists", name),
|
||||
));
|
||||
return Err(anyhow!("stop add_listener {:?} name already exists", name));
|
||||
}
|
||||
}
|
||||
guard.1.push((name.clone(), Box::new(f)));
|
||||
@@ -103,6 +105,18 @@ impl StopManagerInner {
|
||||
thread::park()
|
||||
}
|
||||
}
|
||||
fn wait_timeout(&self, dur: Duration) -> bool {
|
||||
{
|
||||
let mut guard = self.park_threads.lock();
|
||||
guard.push(thread::current());
|
||||
drop(guard);
|
||||
}
|
||||
if self.worker_num.load(Ordering::Acquire) == 0 {
|
||||
return true;
|
||||
}
|
||||
thread::park_timeout(dur);
|
||||
self.worker_num.load(Ordering::Acquire) == 0
|
||||
}
|
||||
fn stop_call(&self) {
|
||||
if let Some(call) = self.stop_call.lock().take() {
|
||||
call();
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
use std::fmt::Display;
|
||||
use std::io;
|
||||
|
||||
#[inline]
|
||||
pub fn io_convert<T, R: Display, F: FnOnce(&io::Error) -> R>(
|
||||
rs: io::Result<T>,
|
||||
f: F,
|
||||
) -> io::Result<T> {
|
||||
rs.map_err(|e| io::Error::new(e.kind(), format!("{},internal error:{:?}", f(&e), e)))
|
||||
}
|
||||
@@ -2,7 +2,6 @@ use crate::util::StopManager;
|
||||
use std::collections::BinaryHeap;
|
||||
use std::{
|
||||
cmp::Ordering,
|
||||
io,
|
||||
sync::mpsc::{sync_channel, Receiver, SyncSender},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
@@ -36,7 +35,7 @@ pub struct Scheduler {
|
||||
sender: SyncSender<Op>,
|
||||
}
|
||||
impl Scheduler {
|
||||
pub fn new(stop_manager: StopManager) -> io::Result<Self> {
|
||||
pub fn new(stop_manager: StopManager) -> anyhow::Result<Self> {
|
||||
let (sender, receiver) = sync_channel::<Op>(32);
|
||||
let s = Self { sender };
|
||||
let s_inner = s.clone();
|
||||
|
||||
@@ -13,6 +13,11 @@ impl Device {
|
||||
Ok(Self { fd: Fd::new(fd)? })
|
||||
}
|
||||
}
|
||||
impl Device {
|
||||
pub fn as_tun_fd(&self) -> &Fd {
|
||||
&self.fd
|
||||
}
|
||||
}
|
||||
impl IFace for Device {
|
||||
fn version(&self) -> io::Result<String> {
|
||||
Ok(String::new())
|
||||
@@ -26,7 +31,7 @@ impl IFace for Device {
|
||||
Err(io::Error::from(io::ErrorKind::Unsupported))
|
||||
}
|
||||
|
||||
fn set_ip(&self, address: Ipv4Addr, mask: Ipv4Addr) -> io::Result<()> {
|
||||
fn set_ip(&self, _address: Ipv4Addr, _mask: Ipv4Addr) -> io::Result<()> {
|
||||
Err(io::Error::from(io::ErrorKind::Unsupported))
|
||||
}
|
||||
|
||||
@@ -34,15 +39,15 @@ impl IFace for Device {
|
||||
Err(io::Error::from(io::ErrorKind::Unsupported))
|
||||
}
|
||||
|
||||
fn set_mtu(&self, value: u32) -> io::Result<()> {
|
||||
fn set_mtu(&self, _value: u32) -> io::Result<()> {
|
||||
Err(io::Error::from(io::ErrorKind::Unsupported))
|
||||
}
|
||||
|
||||
fn add_route(&self, dest: Ipv4Addr, netmask: Ipv4Addr, metric: u16) -> io::Result<()> {
|
||||
fn add_route(&self, _dest: Ipv4Addr, _netmask: Ipv4Addr, _metric: u16) -> io::Result<()> {
|
||||
Err(io::Error::from(io::ErrorKind::Unsupported))
|
||||
}
|
||||
|
||||
fn delete_route(&self, dest: Ipv4Addr, netmask: Ipv4Addr) -> io::Result<()> {
|
||||
fn delete_route(&self, _dest: Ipv4Addr, _netmask: Ipv4Addr) -> io::Result<()> {
|
||||
Err(io::Error::from(io::ErrorKind::Unsupported))
|
||||
}
|
||||
|
||||
|
||||
+3
-1
@@ -3,7 +3,6 @@
|
||||
/// https://github.com/Tazdevil971/tap-windows
|
||||
/// https://github.com/nulldotblack/wintun
|
||||
pub mod device;
|
||||
mod packet;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
@@ -29,3 +28,6 @@ mod windows;
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use windows::Device;
|
||||
|
||||
#[cfg(windows)]
|
||||
mod packet;
|
||||
|
||||
+16
-42
@@ -1,29 +1,27 @@
|
||||
#![allow(dead_code)]
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::os::fd::AsRawFd;
|
||||
use std::process::Command;
|
||||
use std::{io, mem, ptr};
|
||||
|
||||
use libc::{
|
||||
c_char, c_short, ifreq, AF_INET, IFF_MULTI_QUEUE, IFF_NO_PI, IFF_RUNNING, IFF_TAP, IFF_TUN,
|
||||
c_char, c_short, ifreq, AF_INET, IFF_MULTI_QUEUE, IFF_NO_PI, IFF_RUNNING, IFF_TUN,
|
||||
IFF_UP, IFNAMSIZ, O_RDWR, SOCK_DGRAM,
|
||||
};
|
||||
|
||||
use crate::device::IFace;
|
||||
use crate::linux::route;
|
||||
use crate::linux::sys::*;
|
||||
use crate::packet;
|
||||
use crate::unix::{exe_cmd, Fd, SockAddr};
|
||||
|
||||
pub struct Device {
|
||||
name: String,
|
||||
ctl: Fd,
|
||||
tun: Fd,
|
||||
mac: Option<[u8; 6]>,
|
||||
}
|
||||
|
||||
impl Device {
|
||||
pub fn new(name: Option<String>, tap: bool) -> io::Result<Self> {
|
||||
pub fn new(name: Option<String>) -> io::Result<Self> {
|
||||
let device = unsafe {
|
||||
let dev = match name {
|
||||
Some(name) => {
|
||||
@@ -50,7 +48,7 @@ impl Device {
|
||||
);
|
||||
}
|
||||
|
||||
let device_type: c_short = if tap { IFF_TAP } else { IFF_TUN } as c_short;
|
||||
let device_type: c_short = IFF_TUN as c_short; //if tap { IFF_TAP } else { IFF_TUN } as c_short;
|
||||
|
||||
let queues_num = 1;
|
||||
|
||||
@@ -73,29 +71,11 @@ impl Device {
|
||||
let name = CStr::from_ptr(req.ifr_name.as_ptr())
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
let mac = if tap {
|
||||
let get_mac_cmd = format!("cat /sys/class/net/{}/address", name);
|
||||
let mac_out = exe_cmd(&get_mac_cmd)?;
|
||||
let mac_str = String::from_utf8(mac_out.stdout).unwrap();
|
||||
let mut mac = [0; 6];
|
||||
let mut split = mac_str.split(":");
|
||||
for i in 0..6 {
|
||||
mac[i] = u8::from_str_radix(&split.next().unwrap()[..2], 16).unwrap();
|
||||
}
|
||||
Some(mac)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let set_txqueuelen = format!("ifconfig {} txqueuelen 1000", name);
|
||||
if let Err(e) = exe_cmd(&set_txqueuelen){
|
||||
log::warn!("{:?}",e);
|
||||
}
|
||||
Device {
|
||||
name,
|
||||
tun,
|
||||
ctl,
|
||||
mac,
|
||||
let set_txqueuelen = format!("ifconfig {} txqueuelen 1000", name);
|
||||
if let Err(e) = exe_cmd(&set_txqueuelen) {
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
Device { name, tun, ctl }
|
||||
};
|
||||
device.enabled(true)?;
|
||||
Ok(device)
|
||||
@@ -234,6 +214,12 @@ impl Device {
|
||||
}
|
||||
}
|
||||
|
||||
impl Device {
|
||||
pub fn as_tun_fd(&self) -> &Fd {
|
||||
&self.tun
|
||||
}
|
||||
}
|
||||
|
||||
impl IFace for Device {
|
||||
fn version(&self) -> io::Result<String> {
|
||||
Ok(String::new())
|
||||
@@ -286,22 +272,10 @@ impl IFace for Device {
|
||||
}
|
||||
|
||||
fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if self.mac.is_some() {
|
||||
packet::read_tap(
|
||||
buf,
|
||||
|eth_buf| self.tun.read(eth_buf),
|
||||
|eth_buf| self.tun.write(eth_buf),
|
||||
)
|
||||
} else {
|
||||
self.tun.read(buf)
|
||||
}
|
||||
self.tun.read(buf)
|
||||
}
|
||||
|
||||
fn write(&self, buf: &[u8]) -> io::Result<usize> {
|
||||
if let Some(mac) = &self.mac {
|
||||
packet::write_tap(buf, |eth_buf| self.tun.write(eth_buf), mac)
|
||||
} else {
|
||||
self.tun.write(buf)
|
||||
}
|
||||
self.tun.write(buf)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(dead_code)]
|
||||
use std::ffi::{c_void, CStr};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::os::fd::AsRawFd;
|
||||
@@ -224,6 +225,11 @@ impl Device {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Device {
|
||||
pub fn as_tun_fd(&self) -> &Fd {
|
||||
&self.tun
|
||||
}
|
||||
}
|
||||
|
||||
impl IFace for Device {
|
||||
fn version(&self) -> io::Result<String> {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(dead_code)]
|
||||
use std::{fmt, io};
|
||||
|
||||
/// 地址解析协议,由IP地址找到MAC地址
|
||||
|
||||
@@ -21,7 +21,10 @@ impl<B: AsRef<[u8]>> EthernetPacket<B> {
|
||||
let packet = EthernetPacket::unchecked(buffer);
|
||||
//头部固定14位
|
||||
if packet.buffer.as_ref().len() < 14 {
|
||||
Err(io::Error::new(io::ErrorKind::InvalidData,format!("len={}", packet.buffer.as_ref().len())))?;
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("len={}", packet.buffer.as_ref().len()),
|
||||
))?;
|
||||
}
|
||||
|
||||
Ok(packet)
|
||||
|
||||
@@ -13,7 +13,7 @@ where
|
||||
let mut eth_buf = [0; 65536];
|
||||
loop {
|
||||
let len = read_fn(&mut eth_buf)?;
|
||||
if len == 0{
|
||||
if len == 0 {
|
||||
return Ok(len);
|
||||
}
|
||||
//处理arp包
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use libc::{fcntl, F_GETFL, F_SETFL, O_NONBLOCK};
|
||||
use std::io;
|
||||
use std::os::fd::{AsRawFd, IntoRawFd, RawFd};
|
||||
|
||||
@@ -10,6 +11,12 @@ impl Fd {
|
||||
}
|
||||
Ok(Fd(value))
|
||||
}
|
||||
pub fn set_nonblock(&self) -> io::Result<()> {
|
||||
match unsafe { fcntl(self.0, F_SETFL, fcntl(self.0, F_GETFL) | O_NONBLOCK) } {
|
||||
0 => Ok(()),
|
||||
_ => Err(io::Error::last_os_error()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Fd {
|
||||
@@ -51,6 +58,7 @@ impl IntoRawFd for Fd {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
impl Drop for Fd {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod fd;
|
||||
|
||||
pub use fd::Fd;
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
use std::process::Output;
|
||||
#[cfg(any(target_os = "macos", target_os = "linux"))]
|
||||
mod sockaddr;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#![allow(dead_code)]
|
||||
use crate::windows::exe_cmd;
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::{io, process};
|
||||
|
||||
/// 设置网卡名称
|
||||
pub fn set_interface_name(old_name: &str, new_name: &str) -> io::Result<()> {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(dead_code)]
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use winapi::shared::ifdef::NET_LUID;
|
||||
@@ -11,8 +12,6 @@ use winapi::um::winnt::{
|
||||
|
||||
use crate::device::IFace;
|
||||
use crate::packet;
|
||||
use crate::packet::ethernet::protocol::Protocol;
|
||||
use crate::packet::{arp, ethernet};
|
||||
use crate::windows::{ctl_code, decode_utf16, encode_utf16, ffi, netsh, route};
|
||||
|
||||
/* Present in 8.1 */
|
||||
@@ -97,7 +96,7 @@ impl Device {
|
||||
let index = ffi::luid_to_index(&luid).map(|index| index as u32)?;
|
||||
// 设置网卡跃点
|
||||
if let Err(e) = netsh::set_interface_metric(index, 0) {
|
||||
log::warn!("{:?}",e);
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
let device = Self {
|
||||
handle,
|
||||
@@ -122,8 +121,6 @@ impl Device {
|
||||
}
|
||||
}
|
||||
|
||||
const MAC: [u8; 6] = [0xf, 0xf, 0xf, 0xf, 0xe, 0x9];
|
||||
|
||||
impl IFace for Device {
|
||||
fn version(&self) -> io::Result<String> {
|
||||
let mut version = [0u32; 3];
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use libloading::{Error, Library};
|
||||
#![allow(dead_code)]
|
||||
use libloading::Library;
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
@@ -84,7 +85,7 @@ impl Device {
|
||||
//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
|
||||
|
||||
let guid_struct: wintun_raw::GUID = unsafe { std::mem::transmute(guid) };
|
||||
let guid_struct: wintun_raw::GUID = std::mem::transmute(guid);
|
||||
let guid_ptr = &guid_struct as *const wintun_raw::GUID;
|
||||
|
||||
//SAFETY: the function is loaded from the wintun dll properly, we are providing valid
|
||||
@@ -118,7 +119,7 @@ impl Device {
|
||||
let index = ffi::luid_to_index(&std::mem::transmute(luid)).map(|index| index as u32)?;
|
||||
// 设置网卡跃点
|
||||
if let Err(e) = netsh::set_interface_metric(index, 0) {
|
||||
log::warn!("{:?}",e);
|
||||
log::warn!("{:?}", e);
|
||||
}
|
||||
Ok(Self {
|
||||
luid: std::mem::transmute(luid),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#![allow(dead_code)]
|
||||
use log::*;
|
||||
|
||||
use crate::windows::tun::wintun_raw;
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_camel_case_types)]
|
||||
/* automatically generated by rust-bindgen 0.59.1 */
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
|
||||
Reference in New Issue
Block a user